IndexError:列表索引超出范围-用虚拟变量填充

Vin*_*ink 0 python list

我有一个60,000个列表。每个列表的范围是2-5个值。

我需要用每个列表中的第三个值创建一个新列表。

该列表还需要保留60,000个条目。

如果使用第二个值进行此操作,则将执行以下操作:

big_list = [['this', 'is', 'a list'], ['list' 'two'], ['here', 'is', 'another one']]

new_list = [value[1] for value in big_list]
Run Code Online (Sandbox Code Playgroud)

并且new_list会是

['is', 'two', 'is']
Run Code Online (Sandbox Code Playgroud)

在实际程序中new_list,现在将是从每个列表中的第二个值创建的60,000个值的列表。new_list保持相同的长度很重要。

现在,因为如果我尝试,某些列表只有2个值长

new_list = [value[2] for value in big_list]
Run Code Online (Sandbox Code Playgroud)

我很好 IndexError: list index out of range

我需要结果是

['a list', 'dummy variable', 'another one']
Run Code Online (Sandbox Code Playgroud)

有什么办法可以为只有2个值的列表预设一个虚拟变量,而无需更改任何内容big_list?虚拟变量可以是随机字符串,也可以是列表中的先前值。如果我不清楚,请告诉我,谢谢您的帮助。

And*_*ely 5

您可以使用itertools.zip_longestdoc):

big_list = [['this', 'is', 'a list'], ['list', 'two'], ['here', 'is', 'another one']]

from itertools import zip_longest

new_list = [value[2] for value in zip(*zip_longest(*big_list, fillvalue='dummy variable'))]
print(new_list)
Run Code Online (Sandbox Code Playgroud)

印刷品:

['a list', 'dummy variable', 'another one']
Run Code Online (Sandbox Code Playgroud)