Reputation: 163
Say I have a list with single length elements;
['z', 'x', 'y']
And another list with two length elements;
[('x', 7), ('y', 1), ('z', 5)]
How can I rearrange the second list so that the first elements of it(i.e. x, y, z...) are in the exact order of those in the first list (i.e. z, x, y) so that I get an output;
[('z', 5), ('x', 7), ('y', 1)]
Upvotes: 0
Views: 99
Reputation: 59315
You can use this method:
>>> list1 = ['z', 'x', 'y']
>>> list2 = [('x', 7), ('y', 1), ('z', 5)]
>>> dict2 = dict(list2)
>>> new_list = [(key, dict2[key]) for key in list1]
>>> new_list
[('z', 5), ('x', 7), ('y', 1)]
Upvotes: 0
Reputation: 8853
The second list can be trivially transformed into a dictionary, then list comprehensions make it trivial:
a = ['z', 'x', 'y']
b = dict([('x', 7), ('y', 1), ('z', 5)])
c = [(key, b[key]) for key in a]
Upvotes: 2