> I have 2 lists > a = [(4, 1), (7, 3), (3, 2), (2, 4)] > b = [2, 4, 1, 3] > > Now, I want to order _a_ (a[1]) based on _b_. > i.e. the second element in tuple should be the same as > b. > i.e. Output would be [(3, 2), (2, 4), (4, 1), (7, 3)] > > I did the same as follows: > >>> l = len(a) * [None] > >>> for (k, v) in a: > ... for i, e in enumerate(b): > ... if e == v: > ... l[i] = (k, v) >
Essentially, you're sorting a list. The Pythonic approach is to use the sort() function, hiding the details in a "custom comparison function": def compare_func(first, second): b = [2, 4, 1, 3] return cmp(b.index(first[1]), b.index(second[1])) if __name__ == '__main__': a = [(4, 1), (7, 3), (3, 2), (2, 4)] a.sort(cmp=compare_func) print a -John -- http://mail.python.org/mailman/listinfo/python-list