在Python中迭代列表或元组会有什么不同吗?

2024-09-19 23:40:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试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']:
    ...

这纯粹是个人偏好,还是有更多的理由支持使用元组?我只能考虑速度,但我无法想象这会有什么不同

我想我已经看到越来越多的人使用列表,我想知道是否有理由改变它


Tags: andinforsetsdonicklistsperson
1条回答
网友
1楼 · 发布于 2024-09-19 23:40:18

使用列表而不是元组作为常量在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。如果你有选择权,你也应该这样做

相关问题 更多 >