python的sorted怎么用-Python教程

资源魔 38 0

列表有本人的sort办法,其对列表进行旧址排序,既然是旧址排序,那显然元组不成能领有这类办法,由于元组是不成修正的。

排序,数字、字符串依照ASCII,中文依照unicode从小到年夜排序

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

假如需求一个排序好的正本,同时放弃原有列表没有变,怎样完成呢?

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]

留意:y = x[:] 经过分片操作将列表x的元素全副拷贝给y,假如简略的把x赋值给y:y = x,y以及x仍是指向同一个列表,并无孕育发生新的正本。

另外一种猎取已排序的列表正本的办法是应用sorted函数:

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前往一个有序的正本,而且类型老是列表,以下:

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)

以上就是python的sorted怎样用的具体内容,更多请存眷资源魔其它相干文章!

标签: python教程 python编程 python使用问题 sorted

抱歉,评论功能暂时关闭!