Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 python的sorted怎么用

python的sorted怎么用

发布时间:2020-11-09   编辑:www.jquerycn.cn
jquery中文网为您提供python的sorted怎么用等资源,欢迎您收藏本站,我们将为您提供最新的python的sorted怎么用资源

列表有自己的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怎么用的详细内容,更多请关注jquery中文网其它相关文章!

  • 本文原创发布jQuery中文网,转载请注明出处,感谢您的尊重!
  • 您可能感兴趣的文章:
    python中列表怎么排序
    python的sorted怎么用
    Python字典怎么从小到大输出
    python怎么逆序
    python怎么升序和降序排序
    python怎么输出倒序
    怎么使用python对字典进行排序?
    学会Lambda,让程序Pythonic一点
    python中sorted是什么
    Python排序傻傻分不清?一文看透sorted与sort用法

    [关闭]