gpt4 book ai didi

python - 如果你在 Python 中迭代一个列表或一个元组,它会有所不同吗?

转载 作者:行者123 更新时间:2023-12-03 13:32:35 25 4
gpt4 key购买 nike

我目前正在尝试 wemake-python-styleguide并找到 WPS335 :

Using lists, dicts, and sets do not make much sense. You can use tuples instead. Using comprehensions implicitly create a two level loops, that are hard to read and deal with.


它给出了这个例子:
# Correct:
for person in ('Kim', 'Nick'):
...

# Wrong:
for person in ['Kim', 'Nick']:
...
这纯粹是个人偏好还是有更多说明使用元组?我只能考虑速度,但我无法想象这会有什么不同。
我想我已经看到更多人使用列表,我想知道是否有理由改变它。

最佳答案

使用列表而不是元组作为常量在 CPython 中没有区别。在某些版本中,两者都被编译为元组。

>>> dis.dis("""
... for person in ["Kim", "Nick"]:
... ...
... """)
2 0 SETUP_LOOP 12 (to 14)
2 LOAD_CONST 0 (('Kim', 'Nick'))
4 GET_ITER
>> 6 FOR_ITER 4 (to 12)
8 STORE_NAME 0 (person)

3 10 JUMP_ABSOLUTE 6
>> 12 POP_BLOCK
>> 14 LOAD_CONST 1 (None)
16 RETURN_VALUE
请注意列表文字是如何转换为 LOAD_CONST (('Kim', 'Nick')) 的元组的指令。

至于偏好,CPython 更喜欢 tuple .如果你有选择,你也应该这样做。

关于python - 如果你在 Python 中迭代一个列表或一个元组,它会有所不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63954751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com