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
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]]
>>li2 = [[li2[i1] for i1 in range(len(li1))) if li1[i1]==idx] for idx in sorted (set(li1))]
© 2024 OneMinuteCode. All rights reserved.