简体   繁体   中英

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:

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() :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM