Python: How to make one-to-one correspondence of two lists

created at 07-26-2021 views: 18

Demand

There are two lists: A and B. The date is stored in A, and the output under that date is stored in B. It is required to sort by output and the date list will be sorted accordingly.

solution

1. Turn the two lists of A and B into a list of tuple, using the zip() function

zipped = zip(A,B)

print(list(zipped))
  • python2: use print(zipped)
  • python3: use print(list(zipped))

Suppose A = [1,2,3], B = [6,5,4]

then zipped = [(1,6), (2,5), (3,4)]

Sort

sort_zipped = sorted(zipped,key=lambda x:(x[1],x[0]))
# First sort by x[1], if x[1] is the same, then sort by x[0]

At this time sort_zipped = [(3,4), [2,5], [1,6]]

The above code is completed in order of output.

Split

result = zip(*sort_zipped)
# Split sort_zipped into two tuples, as [(3,2,1),(4,5,6)]

x_axis, y_axis = [list(x) for x in result]
# Turn the split two tuples into list lists respectively, which are [3,2,1],[4,5,6]

Above, the problem is solved.

supplement

zip is a generator function, its result is an iterator, the result can only be called once, for example, as shown in the figure below:

The above figure shows that after b is called once, the c called again is empty. If you want to reuse this result, you need to save it in the list, that is:

temp = list(zipped)

Following the example at the beginning of this article, if you print(list(zipped)) directly, then zipped will be empty because you have used up the iterator once.

created at:07-26-2021
edited at: 07-26-2021: