gpt4 book ai didi

python - 遍历Python中的列表列表

转载 作者:IT老高 更新时间:2023-10-28 21:40:53 25 4
gpt4 key购买 nike

我想遍历列表。
我也想遍历列表中不规则嵌套的列表。
谁能告诉我该怎么做?

x = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]

最佳答案

这个 traverse 生成器函数可用于遍历所有值:

def traverse(o, tree_types=(list, tuple)):
if isinstance(o, tree_types):
for value in o:
for subvalue in traverse(value, tree_types):
yield subvalue
else:
yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

关于python - 遍历Python中的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340351/

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