gpt4 book ai didi

python - 遍历 python 中的嵌套列表

转载 作者:行者123 更新时间:2023-11-28 22:58:49 24 4
gpt4 key购买 nike

我试图遍历一个列表,并根据几个条件重新排列子列表中列表中的项目,所有这些都在原始列表中。所以使用下面的 Python 代码,而 list1 通过分组 0s、1s 和 2s 正确打印:

new list 1 = [['A0', 'B0', 'C0'], ['A1', 'B1', 'C1'], ['A2', 'B2', 'C2']]

第二个列表中的所有内容都混淆了,试图通过获取以下内容在进一步的子列表中重新分组 As Bs Cs:

new list 2 = [[['A0', 'A1', 'A2'], ['B0', 'B1', 'B2'], ['C0', 'C1', 'C2']]]

同时期望得到:

new list 1 = [[['A0'], ['B0'], ['C0']], [['A1'], ['B1'], ['C1']], [['A2'], ['B2'], ['C2']]]

下面是我使用的代码(很抱歉,我确定有一个非常精简的版本)。

def Main():

array = ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C1', 'C0', 'C2']

list1 = NewList1(array)
print 'new list 1 = ' + str(list1)

list2 = NewList2(list1)
print 'new list 2 = ' + str(list2)

def NewList1(thelist):
sublist1=[]
sublist2=[]
sublist3=[]
sublist4=[]
newlist=[]
for item in thelist:
if hasattr(item,"__iter__"):
for subitem in item:
sublist1.append(subitem)
elif "0" in item:
sublist2.append(item)
elif "1" in item:
sublist3.append(item)
elif "2" in item:
sublist4.append(item)
else:
newlist.append(item)
if sublist2: newlist.append(sublist2)
if sublist3: newlist.append(sublist3)
if sublist4: newlist.append(sublist4)

if sublist1: newlist.append(NewList1(sublist1))

return newlist


def NewList2(thelist):
sublist1=[]
sublist2=[]
sublist3=[]
sublist4=[]
newlist=[]
for item in thelist:
if hasattr(item,"__iter__"):
for subitem in item:
sublist1.append(subitem)
elif "A" in item:
sublist2.append(item)
elif "B" in item:
sublist3.append(item)
elif "C" in item:
sublist4.append(item)
else:
newlist.append(item)
if sublist2: newlist.append(sublist2)
if sublist3: newlist.append(sublist3)
if sublist4: newlist.append(sublist4)

if sublist1: newlist.append(NewList2(sublist1))

return newlist

Main();

最佳答案

按您的分组标准排序,然后使用 itertools.groupby() :

from itertools import groupby

key = lambda el: el[1]
list2 = [[[el] for el in grouped] for group, grouped in groupby(sorted(input, key=key), key)]

演示:

>>> from itertools import groupby
>>> input = ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C1', 'C0', 'C2']
>>> key = lambda el: el[1]
>>> [[[el] for el in grouped] for group, grouped in groupby(sorted(input, key=key), key)]
[[['A0'], ['B0'], ['C0']], [['A1'], ['B1'], ['C1']], [['A2'], ['B2'], ['C2']]]

您的输出要求有点复杂;如果返回分组元素的列表就足够了,则在 grouped 上调用 list() 就足够了:

>>> [list(grouped) for group, grouped in groupby(sorted(input, key=key), key)]
[['A0', 'B0', 'C0'], ['A1', 'B1', 'C1'], ['A2', 'B2', 'C2']]

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

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