How to use python's sorted

silencement
Release: 2019-06-25 14:50:25
Original
2393 people have browsed it

How to use python's sorted

The list has its own sort method, which sorts the list in-place. Since it is in-place sorting, it is obvious that tuples cannot have this method because tuples cannot be modified.

Sort numbers and strings according to ASCII, Chinese according to unicode from small to large

x = [4, 6, 2, 1, 7, 9] x.sort() print (x) # [1, 2, 4, 6, 7, 9]
Copy after login

If you need a sorted copy while keeping the original list unchanged, how to achieve it?

x = [4, 6, 2, 1, 7, 9] y = x[:] y.sort() print(y) # [1, 2, 4, 6, 7, 9] print(x) # [4, 6, 2, 1, 7, 9]
Copy after login

Note: y = x[:] copies all elements of list x to y through sharding operation. If you simply assign x to y: y = x, y and x still point to the same list. , and no new copies are generated.

Another way to get a copy of a sorted list is to use the sorted function:

x =[4, 6, 2, 1, 7, 9] y = sorted(x) print (y) #[1, 2, 4, 6, 7, 9] print (x) #[4, 6, 2, 1, 7, 9]
Copy after login

sorted returns an ordered copy, and the type is always a list, as follows:

print (sorted('Python')) #['P', 'h', 'n', 'o', 't', 'y']
Copy after login
# 2.有一个list['This','is','a','Boy','!'],所有元素都是字符串,对它进行大小写无关的排序 li=['This','is','a','Boy','!'] l=[i.lower() for i in li] # l1 =l[:] l.sort() # 对原列表进行排序,无返回值 print(l) # print(sorted(l1)) # 有返回值原列表没有变化 # print(l1)
Copy after login

The above is the detailed content of How to use python's sorted. 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
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!