Skip to main content
 首页 » 编程设计

python之将列表转换为 'transposed' 列表

2025年05月04日11grandyang

这可能是一个初学者问题,但我不知道如何寻找答案(因为我无法“命名”问题)

我有 2 个列表或 2 个列表的元组

xxx = ["time1", "time2", "time3"] 
yyy = ["value1", "value2", "value3"] 
zzz=(xxx,yyy) 

现在我想为每个条目创建一个列表/元组 结果应该是

[['time1', 'value1'], ['time2', 'value2'], ['time3', 'value3']] 

我可以使用 for 循环(和 zip)来做到这一点,但是没有“更好”的解决方案吗? 这是一个similar question但我无法使用那里给出的解决方案来解决我的问题

请您参考如下方法:

使用内置 zip功能:

 zzz = zip(xxx, yyy)  

当然,这会创建一个元组列表(或 python3.x 中的可迭代元组)。如果你真的想要一个列表列表:

 #list (python2.x) or iterable(python3.x) of lists 
 zzz = map(list,zip(xxx,yyy))  

或

 #list of lists, not list of tuples 
 #python 2.x and python 3.x 
 zzz = [ list(x) for x in zip(xxx,yyy) ] 

如果你正在使用 python3.x 并且你想确保 zzz 是一个列表,列表压缩解决方案将起作用,或者你可以从 的可迭代对象构造一个列表zip 产生:

#list of tuples in python3.x.   
zzz = list(zip(xxx,yyy)) #equivalent to zip(xxx,yyy) in python2.x 
                         #will work in python2.x, but will make an extra copy. 
                         # which will be available for garbage collection 
                         # immediately