Sook Yee Lim - 3 years ago 150
Python Question

# How to compare a list with a list of list and move them according to the list?

I got this list

``````['a', 'c', 'g', 'w', 'Q', 'front', 'Z']
``````

and a list of list:

``````[[0, 1, 1, 0,a], [1, 0, 2, 0,c], [1, 2, 0, 0,w], [0, 0, 0, 0,Q], [2, 0, 0, 15, 2, 'g'], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]
``````

and I want to swap the items according to my list with the alphabets?So my output will be:

``````[[0, 1, 1, 0,a], [1, 0, 2, 0,c], [2, 0, 0, 15, 2, 'g'],[1, 2, 0, 0,w],[0, 0, 0, 0,Q], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]
``````

EDIT:The numbers have to be moved along with the alphabet.

since @Ajax1234 answer is efficient, But if you want you can try this :

``````list_a = ['a', 'c', 'g', 'w', 'Q', 'front', 'Z']
list_b = [[0, 1, 1, 0,'a'], [1, 0, 2, 0,'c'], [1, 2, 0, 0,'w'], [0, 0, 0, 0,'Q'], [2, 0, 0, 15, 2, 'g'], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]

sorted_list=[]
for i in list_a:
for j in list_b:
if i==j[-1]:
sorted_list.append(j)

print(sorted_list)
``````

In one line solution :

``````print([j for i in list_a for j in list_b if i==j[-1]])
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download