Home  >  Article  >  Backend Development  >  How to use python's sorted

How to use python's sorted

silencement
silencementOriginal
2019-06-25 14:50:252428browse

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]

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]

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]

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

print (sorted('Python')) #['P', 'h', 'n', 'o', 't', 'y']
# 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)

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!

Statement:
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