'Ordering by index in pyhton
I have 3 list like
A = [3,8,10,25] B = [14,15,30,23] C = [24,27,31,34]
I need to combine these 3 lists, then sort them and create 3 lists again with their indexes in python
A = [1,2,3,8] B = [4,5,9,6] C = [7,10,11,12]
Solution 1:[1]
This is a confusing question. However, I think I have found an answer. What you need to do is first create a second, sorted list that combines A, B and C. Then, you need to check where every item in the list goes in the combined list, if that makes sense.
Try this:
A = [3,8,10,25]
B = [14,15,30,23]
C = [24,27,31,34]
combined = sorted(A + B + C)
print(combined)
a = []
b = []
c = []
def order(origin_lst, new_lst):
for i in origin_lst:
new_lst.append(combined.index(i) + 1)
return new_lst
a = order(A, a)
b = order(B, b)
c = order(C, c)
print(a, b, c)
You get an output of: [1, 2, 3, 8] [4, 5, 10, 6] [7, 9, 11, 12] which looks right to me.
Solution 2:[2]
Merge the lists into a flat one, reordering, get the index and regrouping with a slice.
A = [3,8,10,25]
B = [14,15,30,23]
C = [24,27,31,34]
flat = sum((A, B, C), [])
ordered = sorted(flat)
indeces = [ordered.index(i)+1 for i in flat]
A, B, C = [indeces[len(A)*i: len(A)*(i+1)] for i in range(len(flat)//len(A))]
Remark: list.index-based methods are not reliable if the there are repeated values among the lists since it returns the first occurrence.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | cards |
