Home > Net >  Python: Map lists to other ones that are newly ordered
Python: Map lists to other ones that are newly ordered

Time:06-20

I have a list of let's say letters:

l1 = ["a","b","c","d","e","f","g","h","i","j"]

and two lists of values

x1 = [8,2,4,4,3,5,6,7,7,1]
y1 = [2,1,8,1,4,5,9,2,1,2]

I would like to find the simplest way to create a new list l2 that gives letters in the way the lists x2 and y2 are newly ordered:

x2 = [1,2,3,4,4,5,6,7,7,8]
y2 = [2,1,4,1,8,5,9,2,1,2]

I tried some comprehension dictionary, by creating a link between values of (x1,y1) and l1,which didn't work for now.

CodePudding user response:

IIUC, without using l1. You can zip x1 and y1 then sort base x1 then y1 and create x2, y2 like below:

x1 = [8,2,4,4,3,5,6,7,7,1]
y1 = [2,1,8,1,4,5,9,2,1,2]

x2 = []
y2 = []
for x,y in sorted(zip(x1,y1), key= lambda x: (x[0], x[1])):
    x2.append(x)
    y2.append(y)

print(x2)
print(y2)

Output:

[1, 2, 3, 4, 4, 5, 6, 7, 7, 8]
[2, 1, 4, 1, 8, 5, 9, 1, 2, 2]

CodePudding user response:

The question asks, given this list l1, and a list of values l2, how can I reorder the values in l2 and apply the same permutation in l1?

from operator import itemgetter

l1 = ["a","b","c","d","e","f","g","h","i","j"]
x1 = [8,2,4,4,3,5,6,7,7,1]
y1 = [2,1,8,1,4,5,9,2,1,2]

values = list(zip(x1, l1, y1))
values.sort(key=itemgetter(0))
x2, l2, y2 = zip(*values)

The first line after the declaration gives you a list of triplets. The sort function using key=itemgetter(0), is slightly more complex. It uses the itemgetter function to return a function that selects the 0th value from an object that is indexable, i.e. tuple, list, or dict. The third line unpacks the elements into the lists that you wanted.

You can then modify the key=function argument to your liking to get different permutations.

CodePudding user response:

You didn't properly explain how y2 is sorted but it appears to be shuffled to correspond with the reordering of x2 relative to x1. In other words, like this:

x1 = [8,2,4,4,3,5,6,7,7,1]
y1 = [2,1,8,1,4,5,9,2,1,2]
sorted_x_idx = sorted((x, idx) for idx, x in enumerate(x1))
y2 = [y1[idx] for x, idx in sorted_x_idx]

In that case, you can use the same pattern for l1.

  • Related