Python遍历元组数据结构中的列表

2024-09-29 01:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据结构:

data = (['test1','test2','test3'], ['foo1','foo2','foo3'], ['bar1','bar2','bar3'])

我想遍历这个数据结构,并创建一个新的元组,将每个列表的位置1附加到元组中。我想用

(test1,foo1,bar1), (test2,foo2,bar2), (test3,foo3,bar3)

Tags: 数据结构列表data元组test1test2test3foo1
2条回答

这是一个简单的^{}argument unpacking

print zip(*data)

例如:

>>> data = (['test1','test2','test3'],['foo1','foo2','foo3'],['bar1','bar2','bar3'])
>>> zip(*data)
[('test1', 'foo1', 'bar1'), ('test2', 'foo2', 'bar2'), ('test3', 'foo3', 'bar3')]

通过zip()解压:

>>> data = (['test1','test2','test3'],['foo1','foo2','foo3'],['bar1','bar2','bar3'])
>>> zip(*data)
[('test1', 'foo1', 'bar1'), ('test2', 'foo2', 'bar2'), ('test3', 'foo3', 'bar3')]

另请参见:Unzipping and the * operator。你知道吗

相关问题 更多 >