sort函数pythonreverse,sort()和reverse()函数不起作用

I was trying to test how the lists in python works according to a tutorial I was reading.

When I tried to use list.sort() or list.reverse(), the interpreter gives me None.

Please let me know how I can get a result from these two methods:

a = [66.25, 333, 333, 1, 1234.5]

print(a.sort())

print(a.reverse())

解决方案

.sort() and .reverse() change the list in place and return None See the mutable sequence documentation:

The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don’t return the sorted or reversed list.

Do this instead:

a.sort()

print(a)

a.reverse()

print(a)

or use the sorted() and reversed() functions.

print(sorted(a)) # just sorted

print(list(reversed(a))) # just reversed

print(a[::-1]) # reversing by using a negative slice step

print(sorted(a, reverse=True)) # sorted *and* reversed

These methods return a new list and leave the original input list untouched.

Demo, in-place sorting and reversing:

>>> a = [66.25, 333, 333, 1, 1234.5]

>>> a.sort()

>>> print(a)

[1, 66.25, 333, 333, 1234.5]

>>> a.reverse()

>>> print(a)

[1234.5, 333, 333, 66.25, 1]

And creating new sorted and reversed lists:

>>> a = [66.25, 333, 333, 1, 1234.5]

>>> print(sorted(a))

[1, 66.25, 333, 333, 1234.5]

>>> print(list(reversed(a)))

[1234.5, 1, 333, 333, 66.25]

>>> print(a[::-1])

[1234.5, 1, 333, 333, 66.25]

>>> print(sorted(a, reverse=True))

[1234.5, 333, 333, 66.25, 1]

>>> a # input list is untouched

[66.25, 333, 333, 1, 1234.5]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值