我想得到4行的列表内容

2024-09-30 16:22:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析excel并按4行列出清单。 现在我写了

book3 = xlrd.open_workbook('./data/excel1.xlsx')
sheet3 = book3.sheet_by_index(0)

tag_list = sheet3.row_values(0)
user_id = tag_list[9]
for row_index in range(7, sheet3.nrows):
    row = sheet3.row_values(row_index)
    print(row)

在打印(行)中,显示

['', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M, 'N', 'O', '', '', '', '']
['', 'u1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']
['', '500~1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']
['', 'd500', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']
・・・・・

现在我想把这些单子改成4个

[ ['', '', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M, 'N', 'O', '', '', '', '']
    ['', 'u1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']
    ['', '500~1000', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']
    ['', 'd500', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '×', '', '', '', '']]
    ・・・・・

为了做我理想的事情,我应该写些什么呢?我怎样才能解决这个问题?你知道吗


Tags: dataindextagopenexcellistrowworkbook
3条回答

最具霸气的方式是列表理解:

all_rows = [sheet3.row_values(row_index) for row_index in range(7, sheet3.nrows)]
fourrows=[] //place holder
for row_index in range(7, sheet3.nrows):
    row = sheet3.row_values(row_index)
    if len(fourrows)==4:
       print(fourrows)
       fourrows=[]
    fourrows.append(row) // I put this here as there is a chance of printing an extra empty list at the end if we've perfect four multiples.
print(fourrows)

fourrows收集行,直到行数为4。
一旦填充了四行,它就会打印出所有四行,并清空fourrows列表。
它一直持续到没有更多的
注意,最后一次迭代打印出剩余的1/2/3或4行。你知道吗

或者python的方法是。。。你知道吗

for i in range(7, sheet3.nrows,4):
   print([sheet3.row_values(row_index) for row_index in range(i, min(i+4,sheet3.nrows))])

用这些更改替换代码。我已经在列表中创建了,excel文件的每一行都被添加到这个列表中。你知道吗

final_list = []
book3 = xlrd.open_workbook('./data/excel1.xlsx')
sheet3 = book3.sheet_by_index(0)

tag_list = sheet3.row_values(0)
user_id = tag_list[9]
for row_index in range(7, sheet3.nrows):
    row = sheet3.row_values(row_index)
    final_list.append(row)
print(row)

相关问题 更多 >