我有一份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]而new_list会是
['is', 'two', 'is']在实际的程序中,new_list现在是一个包含60,000个值的列表,这些值是从每个列表中的第二个值创建的。重要的是,new_list保持相同的长度。
现在,因为如果我尝试的话,有些列表只有2个值
new_list = [value[2] for value in big_list]我得到了一个很好的IndexError: list index out of range
我需要的结果是
['a list', 'dummy variable', 'another one']有没有办法在不改变big_list中任何东西的情况下,为只有2个值的列表预置一个虚拟变量?伪变量可以是随机字符串,也可以是列表中的前一个值。如果我说得不清楚,请告诉我&谢谢你的帮助。
发布于 2019-07-17 03:58:33
您可以使用itertools.zip_longest (doc):
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)打印:
['a list', 'dummy variable', 'another one']https://stackoverflow.com/questions/57064522
复制相似问题