Jamie Cook
Jamie Cook

Reputation: 25

Sorting a nested list based on another nested list

I have two nested lists, x1 and x2. I need to resort x2 based on the order of x1[0][0].

I have tried to used sort() and some of lambda x but not entirely sure how to approach this.

x1 = [["d", 0.4, 1],
     ["c", 0.5, 2],
     ["b", 0.3, 3],
     ["a", 0.5, 4]]

x2 = [["c", 4, 1],
     ["d", 2, 2],
     ["a", 6, 3],
     ["b", 6, 4]]

I expect to get the following output for the reordered x2

x2 = [["d", 2, 2],
     ["c", 4, 1],
     ["b", 6, 4],
     ["a", 6, 3]]

I can't rely on reordering based on alphabetical order as the dataset I am using differs to this and I may run into other problems. Ideally, I need to write something that will simply match each nested list to the order x2 appears in x1 based only on the first element of each nested list (which is always a string).

I need to do this using only pythons standard library.

Upvotes: 1

Views: 98

Answers (2)

blhsing
blhsing

Reputation: 106883

You can build a dict that maps the keys in x1 to its index using enumerate, and then sort x2 with a key function that returns the index from the mapped key:

order = {k: i for i, (k, *_) in enumerate(x1)}
x2.sort(key=lambda t: order[t[0]])

x2 becomes:

[['a', 3], ['b', 1], ['c', 4], ['d', 2]]

Upvotes: 5

avloss
avloss

Reputation: 2646

try following:

x1 = [["a", 1],
     ["b", 2],
     ["c", 3],
     ["d", 4]]

x2 = [["b", 1],
     ["d", 2],
     ["a", 3],
     ["c", 4]]

x2.sort(key=lambda k: dict(x1)[k[0]])

x2

this outputs

[['a', 3], ['c', 4], ['b', 1], ['d', 2]]

Upvotes: 2

Related Questions