簡體   English   中英

在python中按另一個list.index對壓縮列表進行排序

[英]Sort zipped lists by another list.index in python

如何從另一個列表中排序列表索引的郵政列表? 目前我使用兩個循環,效率不高。

L1 = ['eins','zwei','drei','vier']
L2 = ['zwei','eins','vier','drei']
L3 = ['apfel','birne','banane','kirsche']

zipped = zip(L2,L3)
L4 = []

for i in L1:
    for e,g in zipped:
        if e == i:
            L4.append(g)

print L4

使用python字典:

d = dict(zip(L2,L3))
L4 = [d[key] for key in L1]

要按另一個列表的index對壓縮列表進行排序,可以使用sorted()函數:

l1 = ['eins', 'zwei', 'drei', 'vier']
l2 = ['zwei', 'eins', 'vier', 'drei']
l3 = ['apfel', 'birne', 'banane', 'kirsche']

l = sorted(zip(l2, l3), key=lambda x: l1.index(x[0]))
# [('eins', 'birne'), ('zwei', 'apfel'), ('drei', 'kirsche'), ('vier', 'banane')]

[i for _, i in l]
# ['birne', 'apfel', 'kirsche', 'banane']

按照你原來的邏輯,我想,你可以改變一點讓它工作:

L4 = []

for e in L1:
  i2 = L2.index(e) # looks for the index (i2) of the element e of L1 in L2
  L4.append(L3[i2]) # append lo L4 the element at index i2 in L3

print(L4)
#=> ['birne', 'apfel', 'kirsche', 'banane']

哪個可以寫成一個班輪:

[ L3[L2.index(e)] for e in L1 ]

我喜歡@syltruong的答案,但enumerate是另一個選擇:

for item1 in L1:
    for index, item2 in enumerate(L2):
        if item1 == item2:
            L4.append(L3[index])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM