Python里的sort()和sorted()可以用来排序列表,它们之间有什么区别?什么时候使用sort或sorted?

如果要对列表进行排序,但仍具有原始的排序方式,则可以使用该sorted()功能。如果不想保持列表的原始顺序,则可以sort()在列表上调用该函数。

 

列表sort()函数和sorted()函数之间的主要区别在于sort()函数会修改被调用的列表。

而sorted()函数将创建一个新列表,其中包含给定列表的排序版本。sorted()函数将不会修改作为参数传递的列表。

 

第二个重要区别是sorted()函数将返回一个列表,因此您必须将返回的数据分配给新变量。

而sort()函数就地修改列表,并且没有返回值。

下面的示例显示sort()sorted()之间的差别。

 

vegetables = ['squash', 'pea', 'carrot', 'potato']

new_list = sorted(vegetables)

# output: new_list = ['carrot', 'pea', 'potato', 'squash']
print(new_list)

# output:  vegetables = ['squash', 'pea', 'carrot', 'potato']
print(vegetables)

# 传递给后sorted(),vegetables列表保持不变。

vegetables = ['squash', 'pea', 'carrot', 'potato']

vegetables.sort()

#output: vegetables = ['carrot', 'pea', 'potato', 'squash']
print(vegetables)

# 一旦sort()调用该函数,列表就会更新。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值