Home >Backend Development >Python Tutorial >How to sort python tuples
How to sort python tuples: first convert the tuple into a list; then use the sort() or sorted() method to sort the converted list; finally convert the sorted list back to a tuple Just group.
Tuple tuple is an immutable data type. The elements in the tuple cannot be modified, deleted, or added. Tuples are restricted lists. Tuples cannot be sorted.
Lists in Python are mutable objects. Mutable objects can be sorted, such as: L.sort() or sorted(L), but in tuple data structures, because tuples are immutable Object does not provide these methods in the list. The method is to convert the tuple into a list first, sort the converted list, and then convert it back to the tuple. This completes the sorting of tuples.
[Method 1:]Use the L.sort() method in the list
>>> T = (11, 33, 22, 44) # 元组对象 >>> L = list(T) # 转变为列表对象 >>> L.sort() # 用sort()函数对列表进行排序 >>> L # 排序后的顺序 [11, 22, 33, 44] >>> T = tuple(L) # 再将列表转换回元组 >>> T (11, 22, 33, 44)
[Method 2:]Use the sorted() method in the list L) Method
>>> T = (11, 33, 22, 44) # 元组对象 >>> L = list(T) # 转变为列表对象 >>> L = sorted(L) # 对列表对象排序 >>> T = tuple(L) # 再将排序好的列表对象转换为元组 >>> T (11, 22, 33, 44)
Note:
1. Pay attention to the difference between sort() and sorted()
2.sort() Modify the other table object in place, and the return value is None, so there is no need to receive new variables here!
3.sorted() will modify the copy of the list object and return the modified value, so a variable must be used here to receive it!
The above is the detailed content of How to sort python tuples. For more information, please follow other related articles on the PHP Chinese website!