How to sort python tuples

(*-*)浩
Release: 2020-09-18 15:59:39
Original
22228 people have browsed it

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.

How to sort python tuples

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)
Copy after login

[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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!