Python 2 与 Python 3 中字符串与列表比较的示例

问题描述 投票:0回答:1

我正在研究 Python 2 和 Python 3 之间的差异。有人提到字符串到列表的比较在 Python 3 中不起作用,因为它们的价值有限。我正在尝试找一个这样的例子。这是我尝试过的:

Python 2.7.18 (default, Jun 23 2024, 08:39:49)
[GCC Apple LLVM 15.0.0 (clang-1500.3.9.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['a', 'b', 'c']
>>> print 'abc' == mylist
False
>>>

因为 3 == 3 ^^^ 不应该返回 True 吗?

Python 3.12.0 (main, Nov 29 2023, 07:31:13) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['a', 'b', 'c']
>>> print('abc' == mylist)
False

我以为 Python 3 会因此而生我的气?

Python 3.12.0 (main, Nov 29 2023, 07:31:13) [Clang 15.0.0 (clang-1500.0.40.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['a', 'b', 'c']
>>> print('abc' >= mylist)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'list

好吧,这似乎是正确的,但为什么支持

==

python python-3.x python-2.7
1个回答
0
投票

不。您正在将 ['a', 'b', 'c'] 与 'abc' 进行比较。两个截然不同的事情。如果你愿意的话,你可以尝试制作一个新的字符串并将它们连接在一起。这是代码:

>>> mylist = ['a', 'b', 'c']
>>> print 'abc' == mylist.join("")

我希望这有帮助!

-完全不是ADev:)

© www.soinside.com 2019 - 2024. All rights reserved.