【问题标题】:Turn multiple lists into one list in python [duplicate]在python中将多个列表变成一个列表[重复]
【发布时间】:2016-06-15 13:37:47
【问题描述】:

我有一个电子表格,其中包含我使用以下代码导入 python 的数据;

import xlrd

wb = xlrd.open_workbook('data.xls')

sh = wb.sheet_by_index(0)

for rownum in range(sh.nrows):
    print sh.row_values(rownum)

这会打印出电子表格的每一行;例如。

[13.0, 2.0, 92.0, 83.0]
[10.0, 8.0, 80.0, 78.0]
[7.0, 4.0, 121.0, 60.0]

我如何获取这些单独的列表并将它们合并到一个看起来像的列表中;

test = [[13.0, 2.0, 92.0, 83.0], [10.0, 8.0, 80.0, 78.0], [7.0, 4.0, 121.0, 60.0]]

谢谢,

【问题讨论】:

标签: python list merge


【解决方案1】:

只需使用列表推导:

test = [sh.row_values(rownum) for rownum in range(sh.nrows)]

【讨论】:

  • 我知道 OP 本身并不要求这个,但我喜欢你的回答,我认为你可以在其中添加这一点:这可以稍微扩展为 append the names of each column to the row valuesfor row_index in xrange(1, sheet.nrows): test = [ {keys[col_index]: sheet.cell(row_index, col_index).value for col_index in range(sh.ncols)} for row_index in range(sh.nrows) ] 这可能对查看此问题的人有所帮助。
【解决方案2】:

只需在循环之前添加这一行:

final = []

然后将行改为:

final.append(sh.row_values(rownum))

它应该满足你的要求。

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 2013-04-15
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多