這裏產生與子列表長度爲重點,並已表示,所有子列表列表的dict
爲例長度:
a= [[1,2,3],[4,5,6],[3,4],[2,1],[5,6,7],[1,3,5]]
lengths = set([len(l) for l in a])
result = { n : [l for l in a if len(l) == n] for n in lengths}
print(result)
這給:
{2: [[3, 4], [2, 1]], 3: [[1, 2, 3], [4, 5, 6], [5, 6, 7], [1, 3, 5]]}
編輯:
如果你想命名列表,你可以用
a1 = result[2] #[[3, 4], [2, 1]]
a2 = result[3] #[[1, 2, 3], [4, 5, 6], [5, 6, 7], [1, 3, 5]]
編輯2:
a= [[1,2,3],[4,5,6],[3,4],[2,1],[5,6,7],[1,3,5]]
lengths = set([len(l) for l in a])
result = { n : [l for l in a if len(l) == n] for n in lengths}
iter_2 = iter(result[2])
current_2 = result[2][0]
iter_3 = iter(result[3])
current_3 = result[3][0]
a1 = []
a2 = []
for l in a:
if len(l) == 2:
current_2 = next(iter_2)
elif len(l) == 3:
current_3 = next(iter_3)
a1.append(current_2)
a2.append(current_3)
print(a1) #[[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]]
print(a2) #[[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]
編輯3:
另一個
理解什麼OP是要求,這裏產生所需結果的代碼後沒有迭代器的方法是:
a= [[1,2,3],[4,5,6],[3,4],[2,1],[5,6,7],[1,3,5]]
a1=[l if len(l) == 2 else None for l in a]
a2=[l if len(l) == 3 else None for l in a]
for l in a1:
if l is not None:
curr1 = l
break
for l in a2:
if l is not None:
curr2 = l
break
for i in range(len(a)):
if a1[i] is None:
a1[i] = curr1
else:
curr1 = a1[i]
if a2[i] is None:
a2[i] = curr2
else:
curr2 = a2[i]
print(a1) #[[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]]
print(a2) #[[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]
編輯4:
顯然,我變得有點得意忘形,但這裏仍然是與任何類型的子列表長度的工作的廣義解:
a= [[1,2,3],[4,5,6],[3,4],[2,1],[5,6,7],[1,3,5]]
lengths = set([len(l) for l in a])
result = { n : [l if len(l) == n else None for l in a] for n in lengths}
current = {}
for n,res in result.items():
for l in res:
if l is not None:
current[n] = l
break
for i in range(len(a)):
for n,res in result.items():
if res[i] is None:
res[i] = current[n]
else:
current[n] = res[i]
print(result)
給出:
{
2: [[3, 4], [3, 4], [3, 4], [2, 1], [2, 1], [2, 1]],
3: [[1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6], [5, 6, 7], [1, 3, 5]]
}
「該列表的索引順序應該與最初的列表保持一致,並且對於每個不等長的列表,我希望列出一個值作爲其前值的列表vious list「 - 我真的不明白你想做什麼 - )) – marmeladze
@marmeladze,你是對的 –
對不起,我的意思是我不想改變嵌套列表的順序。他們的指數應該保持最初的名單。第二部分,如果你看看所需的輸出,我想你可以得到我的意思 – mahab