What can I change so that I will get a list of only the first row? i.e
0 1
1 2
2 3
3 4
I have tried the below:
matrix = [[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]]
for index in range[len[matrix]]:
print[index,matrix[index][0]]
0 1
1 3
2 4
3 5
asked Nov 3, 2018 at 14:58
Jim GJim G
31 gold badge1 silver badge3 bronze badges
0
You need:
print[index,matrix[0][index]]
instead of:
print[index,matrix[index][0]]
This is because the first index is associated with the outer list [the rows]. matrix[index]
returns an entire row, and then slicing it further returns elements from that row.
You should also change:
for index in range[len[matrix]]:
to:
for index in range[len[matrix[0]]]:
for the same reason. Since it's a square matrix, it'll work out either way, but that's just luck. Actually, it'd be best to just do this instead for simplicity:
for i, e in enumerate[matrix[0]]:
print[i, e]
On each iteration of the loop, enumerate[]
yields a tuple consisting of the index and the element together. If you don't need the index, you could further simplify to:
for e in matrix[0]:
print[e]
You
typically only need to use range[]
if you aren't already starting with a list [or something else that's iterable].
answered Nov 3, 2018 at 15:07
MarredCheeseMarredCheese
14.5k7 gold badges84 silver badges81 bronze badges
This should work:
matrix = [[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]]
for index in range[len[matrix]]:
print[index,matrix[0][index]]
You were trying to get the first element from each individual list, the code above will get all elements from the first list.
answered Nov 3, 2018 at 15:00
MarkMark
4,8882 gold badges21 silver badges29 bronze badges
Assuming your matrix
is a list of rows:
print[matrix[0]]
Or if you want one item per line:
for value in matrix[0]:
print[value]
And if you want the index:
for index, value in enumerate[matrix[0]]:
print[index, value]
answered Nov 3, 2018 at 15:00
Carlos MermingasCarlos Mermingas
3,6722 gold badges20 silver badges39 bronze badges
matrix = [
[1, 2, 3, 4],
[3, 5, 7, 9],
[4, 6, 8, 10],
[5, 7, 9, 11]
]
matrix[0]
gives you the first row, just iterate over it like this:
# ONLY ITERATING OVER THE FIRST ROW
for item in matrix[0]:
print[item]
answered Nov 3, 2018 at 15:06
bhansabhansa
6,9062 gold badges28 silver badges50 bronze badges
Not the answer you're looking for? Browse other questions tagged python python-3.x list or ask your own question.
11 Python code examples are found related to " print rows". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
def print_in_rows[min_dbg_level, str_list, n_cols=5]: """Prints contents of a list in rows `n_cols` entries per row. """ if min_dbg_level > config.debug_level: return ls = len[str_list] n_full_length = int[ls / n_cols] n_rest = ls % n_cols print_str = '\n' for i in range[n_full_length]: print_str += ['"{:}", ' * n_cols].format[*str_list[i * n_cols:[i + 1] * n_cols]] + '\n' print_str += ['"{:}", ' * n_rest].format[*str_list[-n_rest:]] print[print_str.strip[][:-1]]
Example 2
def print_title_rows[self, rows]: """ Set rows to be printed on the top of every page format `1:3` """ if rows is not None: if not ROW_RANGE_RE.match[rows]: raise ValueError["Print title rows must be the form 1:3"] self._print_rows = rows
Example 3
def printRows[self]: if self.lastError is True: return self.processColMeta[] self.printColumnsHeader[] for row in self.rows: for col in self.colMeta: self.__rowsPrinter.logMessage[col['Format'] % row[col['Name']] + self.COL_SEPARATOR] self.__rowsPrinter.logMessage['\n']
Example 4
def print_rows[rows]: # Go through the rows and work out all the widths in each column column_widths = [] for _, columns in rows: if isinstance[columns, six.string_types]: continue for i, column in enumerate[columns]: if i >= len[column_widths]: column_widths.append[[]] # Length of the column [with ansi codes removed] width = len[_strip_ansi[column.strip[]]] column_widths[i].append[width] # Get the max width of each column and add 4 padding spaces column_widths = [ max[widths] + 4 for widths in column_widths ] # Now print each column, keeping text justified to the widths above for func, columns in rows: line = columns if not isinstance[columns, six.string_types]: justified = [] for i, column in enumerate[columns]: stripped = _strip_ansi[column] desired_width = column_widths[i] padding = desired_width - len[stripped] justified.append['{0}{1}'.format[ column, ' '.join['' for _ in range[padding]], ]] line = ''.join[justified] func[line]
Example 5
def print_request_rows[request_rows]: """ Takes in a list of request rows generated from :func:`pappyproxy.console.get_req_data_row` and prints a table with data on each of the requests. Used instead of :func:`pappyproxy.console.print_requests` if you can't count on storing all the requests in memory at once. """ # Print a table with info on all the requests in the list cols = [ {'name':'ID'}, {'name':'Verb'}, {'name': 'Host'}, {'name':'Path', 'width':40}, {'name':'S-Code', 'width':16}, {'name':'Req Len'}, {'name':'Rsp Len'}, {'name':'Time'}, {'name':'Mngl'}, ] print_rows = [] for row in request_rows: [reqid, verb, host, path, scode, qlen, slen, time, mngl] = row verb = {'data':verb, 'color':verb_color[verb]} scode = {'data':scode, 'color':scode_color[scode]} host = {'data':host, 'color':color_string[host, color_only=True]} path = {'data':path, 'formatter':path_formatter} print_rows.append[[reqid, verb, host, path, scode, qlen, slen, time, mngl]] print_table[cols, print_rows]
Example 6
def printRows[self]: if self.lastError is True: return self.processColMeta[] self.printColumnsHeader[] for row in self.rows: for col in self.colMeta: self.__rowsPrinter.logMessage[col['Format'] % row[col['Name']] + self.COL_SEPARATOR]
Example 7
def printRows[self]: if self.lastError is True: return self.processColMeta[] self.printColumnsHeader[] for row in self.rows: for col in self.colMeta: self.__rowsPrinter.logMessage[col['Format'] % row[col['Name']] + self.COL_SEPARATOR]
Example 8
def print_rows[heads, rows, color='']: """Print Column With Color. Params: heads: :list: the row of heads rows: :list tuple: the rows data[list or tuple] coler: :str: lightblack_ex magenta cyan green blue yellow red Returns: return the strings of table """ assert len[heads] == len[rows[0]] assert isinstance[color, str] _prefix = '' if hasattr[Fore, color.upper[]]: _prefix = getattr[Fore, color.upper[]] # # split rows # table = PrettyTable[heads] for row in rows: table.add_row[row] raw = table.get_string[] init[autoreset=True] print[_prefix + raw] return table
Example 9
def printRows[self]: if self.lastError is True: return self.processColMeta[] self.printColumnsHeader[] for row in self.rows: for col in self.colMeta: self.__rowsPrinter.logMessage[col['Format'] % row[col['Name']] + self.COL_SEPARATOR]
Example 10
def print_rows[self]: """Print the rows.""" y = self.y_offset + 1 for row in self.rows[self.row_offset : self.row_offset + self.height]: self.scroller.set_scroll[self.x_scroll] x = self.x_offset for i, column_name in enumerate[self.columns_order]: column = self.columns[column_name] padding = f"