gpt4 book ai didi

Python:列表理解无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:35 25 4
gpt4 key购买 nike

以下是学习过程的一部分,非常感谢您的帮助!

我在对列表理解进行逆向工程时遇到问题。我有一个输入数据列表:

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 引用了错误背后的原因。

然而,这里一个有效的方法可能是:

使用 itertools.zip_longest :

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_longest and not zip to take care of the extra elements, Incase of data like (Notice the red apples and Elon):

tableData = [['red apples', 'apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David', 'Elon'],
['dogs', 'cats', 'moose', 'goose']]

使用 zip 会错过 bananaElon 给出的输出:

[('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)]

关于Python:列表理解无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55282031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com