python中sort、reverse函数与sorted、reversed函数的区别

版权声明:个人博客网址 https://29dch.github.io/ 博主GitHub网址 https://github.com/29DCH,欢迎大家前来交流探讨和fork! https://blog.csdn.net/CowBoySoBusy/article/details/82963245

list.reverse()函数

a = [1,2,3,4,5]
b = a.reverse()
print(a)
print(b)

输出:

[5, 4, 3, 2, 1]
None

可以看出,b.reverse()函数是对a列表进行反转,返回None。

reversed()函数

a = [1,2,3,4,5]
b = list(reversed(a))
print(a)
print(b)

输出:

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

可以看出,reversed()函数对列表进行反转,并返回一个新的迭代器。并不是返回一个新的列表,前面需要加上list()才能得到列表。

同理,list.sort()与sorted()函数情况是一样的:

a = [2,5,1,3,4]
b = a.sort()
c = sorted(a)
print(a)
print(b)
print(c)

输出:
[1, 2, 3, 4, 5]
None
[1, 2, 3, 4, 5]

猜你喜欢

转载自blog.csdn.net/CowBoySoBusy/article/details/82963245