gpt4 book ai didi

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

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

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

我有 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

关于python - 将列表转换为 'transposed' 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302012/

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