简体   繁体   English

关于 Python 中的反向列表的问题

[英]Question about reversed lists in Python

I am very new to python, as you will be able to tell.正如您所知,我对 python 非常陌生。

If I have a list:如果我有一个清单:

a = [1,2,3,2,1]

This evaluates to true:这评估为真:

a == a[::-1]

...but this evaluates to false: ...但这评估为假:

a == a.reverse()

Why is that the case?为什么会这样?

because .reverse() reverses the list in-place and returns none:因为.reverse()就地反转列表并且不返回:

>>> print a.reverse()
None

and a == None evaluates to False .并且a == None评估为False

a.reverse() has no return value, so the comparison is a==None which is false a.reverse()没有返回值,所以比较是 a==None 是假的

you can check with:你可以检查:

>>> str(a.reversed())
'None'

even better:更好:

>>> (id(a.reverse()), id(None))

you'll see the same addresses你会看到相同的地址

If you want a new copy of the list, use reversed() instead.如果您想要列表的新副本,请改用 reversed()。

a == list(reversed(a))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM