2

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

4 Answers 4

4

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']
Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what i tried to achieve but failed with the logic behind lambda, Thanks a lot
4

Use a python dictionary:

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

1 Comment

This answer wins on time: ~800 ns vs. ~1.1 µs for Mykola's answer (not including his last list comprehension)
3

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 ]

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.