繁体   English   中英

如何将多个列表转换为子列表列表,其中每个子列表由所有列表中的相同索引项组成?

[英]How to turn multiple lists into a list of sublists where each sublist is made up of the same index items across all lists?

如何将多个列表转换为一个子列表列表,其中每个子列表由原始列表中相同索引处的项组成?

lsta = ['a','b','c','d']
lstb = ['a','b','c','d']
lstc = ['a','b','c','d']

Desired_List = [['a','a','a'],['b','b','b'],['c','c','c'],['d','d','d']]

我似乎无法在这里使用zip,所以我该怎么做?

使用zip ,在胁迫下:

>>> zip(lsta, lstb, lstc)
[('a', 'a', 'a'), ('b', 'b', 'b'), ('c', 'c', 'c'), ('d', 'd', 'd')]

如果是Python 3,则需要将zip转换为列表:

>>> list(zip(lsta, lstb, lstc))
[('a', 'a', 'a'), ('b', 'b', 'b'), ('c', 'c', 'c'), ('d', 'd', 'd')]

清单列表将如下所示:

>>> [list(x) for x in zip(lsta, lstb, lstc)]
[['a', 'a', 'a'], ['b', 'b', 'b'], ['c', 'c', 'c'], ['d', 'd', 'd']]
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM