简体   繁体   English

在python中按另一个list.index对压缩列表进行排序

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

how can i sort a zip list with list index from another list? 如何从另一个列表中排序列表索引的邮政列表? At the moment i use two loops and its not very efficient. 目前我使用两个循环,效率不高。

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

Use a python dictionary: 使用python字典:

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

To sort zipped lists by index of another list you can use the function sorted() : 要按另一个列表的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']

Following your original logic, I guess, you can change a bit to make it work: 按照你原来的逻辑,我想,你可以改变一点让它工作:

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']

Which can be written as a one liner: 哪个可以写成一个班轮:

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

I like @syltruong answer, but enumerate is one more option: 我喜欢@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