我正在尝试遍历一个列表,并根据几个条件在子列表中重新排列列表中的项目,所有这些都在原始列表中。因此使用 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();