以下是学习过程的一部分,非常感谢您的帮助!
我在对列表理解进行逆向工程时遇到问题。我有一个输入数据列表:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
我想创建一系列新的列表,如下所示:
['apples', 'Alice', 'dogs']
['oranges', 'Bob', 'cats']
['cherries', 'Carol', 'moose']
['banana', 'David', 'goose']
我可以使用:
i = 0
for li in range(4):
out = [item[i] for item in tableData]
print(out)
i += 1
但是,当我尝试使用时:
i = 0
out = []
for li in range(4):
for item in tableData:
out.append(item[i])
print(out)
i += 1
它会导致错误。
知道为什么吗?我怎样才能让它像前面的例子一样工作?
请您参考如下方法:
@Matt B 引用了错误背后的原因。
然而,这里一个有效的方法可能是:
print(list(zip_longest(tableData[0],tableData[1], tableData[2])))
或者更好的是,泛化。 (感谢@Patrick Haugh)
print(list(zip_longest(*tableData)))
输出:
[('apples', 'Alice', 'dogs'), ('oranges', 'Bob', 'cats'), ('cherries', 'Carol', 'moose'), ('banana', 'David', 'goose')]
Note, I used
zip_longestand notzipto take care of the extra elements, Incase of data like (Notice thered applesandElon):
tableData = [['red apples', 'apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David', 'Elon'],
['dogs', 'cats', 'moose', 'goose']]
使用 zip 会错过 banana 和 Elon 给出的输出:
[('red apples', 'Alice', 'dogs'), ('apples', 'Bob', 'cats'), ('oranges', 'Carol', 'moose'), ('cherries', 'David', 'goose')]
但使用 longest_zip 会将缺失值插入为 None:
[('red apples', 'Alice', 'dogs'), ('apples', 'Bob', 'cats'), ('oranges', 'Carol', 'moose'), ('cherries', 'David', 'goose'), ('banana', 'Elon', None)]
