I'd like to sort out the list that stores sequence types

Asked 2 years ago, Updated 2 years ago, 134 views

data1 = [[1,2,3], [4,5,6], [7,8,9]]
data2 = [(1,2,3), (4,5,6), (7,8,9)]

I'm saving lists and tuples as list elements You want to sort by the second item (2,5,8) in each element.

In Python 3.5, the first element is based on data1.sort() I don't know how to change it

sorting list python

2022-09-22 10:46

1 Answers

list.sort (*, key=None, reverse=None) specifies key as the second element

data1 = [[10,11,12], [201,8,3], [4,5,6], [13,8,9]]

data1.sort(key=lambda tup:tup[1])
#data1.sort (key=lambdaup:tup[1], reverse=True) in descending order)

print(data1)

sorted(iterable[, key][, reverse]) returns the list that sorted itable Write method is similar to 1

data1 = [[10,11,12], [201,8,3], [4,5,6], [13,8,9]]

sortedData = sorted(data1, key=lambda tup: tup[1])
#In descending order, sortedData = sorted (data1, key=lambdaup:tup[1], reverted=True)


2022-09-22 10:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.