我是Python的新手,并且正在处理我希望使用python阅读的Excel工作表。我想将行读入列表列表。我已尝试使用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]
但是这给了我一个列表,列出了所有行作为列表。
我想制作不同的列表,其中包含15或12或10行(取决于条件)。
你能帮我吗? 以下是Excel文件示例,获得的输出和预期输出。Expected output和obtained op。我无法附加超过2个附件! 提前谢谢!答案 0 :(得分:0)
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)]
说明:第一个列表推导将返回一个浅列表。第二个列表推导将您的浅列表列表转换为一组列表,这些列表是N个条目长。要了解其工作原理,请考虑以下示例数据:
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']]]
range(1,len(a),N)
将创建一个从1到len(a)
的整数序列,跳过N个数字,以便您可以选择正确的位置来分割您的浅列表。由于[j:j+N]
索引,它抓取了N-1项。