I'm new to Python and working on a Excel sheet that i want to read using python. I want to read the rows into lists of lists. I've tried this using Openpyxl
rows_iter = ws.iter_rows(min_col = 1, min_row = 2, max_col = 11, max_row = ws.max_row)
val1 = [[cell.value for cell in row] for row in rows_iter]
But this gives me a single list of all the rows as lists inside.
I want to make make different lists consisting of 15 or 12 or 10 rows in them (depending on a condition).
Could you please help me. Here are the sample Excel file, obtained output and expected outputs. Expected output and obtained op . I'm not able to attach more than 2 attachments! Thanks in advance!
rows_iter = ws.iter_rows(min_col = 1, min_row = 2, max_col = 11, max_row = ws.max_row)
val_intermediate = [[cell.value for cell in list(row)] for row in rows_iter]
# This would be set to whatever cell value contains N
N = ws['A1'].value
# This splits your shallow list of lists into a list of N lists of lists (!)
val1 = [val_intermediate[j:j+N] for j in range(1,len(val_intermediate),N)]
Explanation: The first list comprehension will return a shallow list of lists. The second list comprehension converts your shallow list of lists into a group of lists of lists that are N entries long. To see how this works, consider this sample data:
In [1]: a = [['a','b','c'],['d','e','f'],['g','h','i'],['j','k','l'] ['m','n','o'],['p','q','r']]
In [2]: N=2; [a[j:j+N] for j in range(1,len(a),N)]
Out[2]:
[[['d', 'e', 'f'], ['g', 'h', 'i']],
[['j', 'k', 'l'], ['m', 'n', 'o']],
[['p', 'q', 'r']]]
In [3]: N=3; [a[j:j+N] for j in range(1,len(a),N)]
Out[3]:
[[['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']],
[['m', 'n', 'o'], ['p', 'q', 'r']]]
The range(1,len(a),N)
will create a sequence of integers from 1 to len(a)
, skipping N numbers, so that's how you can pick the correct locations at which to split your shallow list of lists. It grabs N-1 items because of the [j:j+N]
indexing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.