I want Python to sort one-dimensional arrays in ascending order and associate that information with other arrays.

Asked 2 years ago, Updated 2 years ago, 25 views

When I rearrange li1 in ascending order, I would like li2[i] to be rearranged as if it were tied to the first li1[i] and made into a two-dimensional array.

 li1 = [1, 1, 2, 3, 4, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 2, 3, 4 ]

li2 = [1, 10, 40, 70, 80, 2, 11, 41, 71, 81, 3, 12, 42, 72, 82]

The results should be as follows.

 li1 = [1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4 ]


li2 = [[1, 10, 2, 11, 3, 12], [40, 41, 42], [70, 72], [80, 82]]

Thank you for your cooperation.

python

2022-09-30 21:10

2 Answers

How about groupby by creating a nested list of li1 and li2 corresponding to each element?

#!/usr/bin/python

from operator import itemgetter
from itertools import groupby
from print import print aspp

li1 = [1, 1, 2, 3, 4, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 2, 3, 4 ]
li2 = [1, 10, 40, 70, 80, 2, 11, 41, 71, 81, 3, 12, 42, 72, 82]

merge=zip(li1,li2)
merge.sort(key=itemgetter(0))
group=groupby(merge, itemgetter(0))
li = [[item[1] for item in data] for (key, data) in group]

pp(li)

Output:

[1, 10, 2, 11, 3, 12], [40, 41, 42], [70, 71, 72], [80, 81, 82]]


2022-09-30 21:10

>>li2 = [[li2[i1] for i1 in range(len(li1))) if li1[i1]==idx] for idx in sorted (set(li1))]


2022-09-30 21:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.