Best style for iterating over a small number of items in Python?

余生长醉 提交于 2019-12-11 04:00:04

问题


I was just reading a presentation on python and I noted that the author had missed out the round brackets of the tuple for the items to iterate over, and it struck me that I might be inclined to leave them in. A quick re-read of PEP-8 gave no definitive answer, and I didn't want to 'fall-back' on the old "explicit is better than implicit" without some discussion; so ...

Which do you prefer? Which do you think is more pythonic in these two equivalent for statements (limit the discussion to its use in for statements).

>>> # Some setup
>>> x, y, z = 1, 'Hi', True
>>> 
>>> #Style 1: Implicit tuple
>>> for i in x, y, z:
    print(i)


1
Hi
True
>>> # Style 2: Explicit tuple
>>> for i in (x, y, z):
    print(i)


1
Hi
True
>>> 

回答1:


I'd go with Style 2, as you can actually understand what you are iterating over:

>>> # Style 2: Explicit tuple
>>> for i in (x, y, z):
        print(i)

Style 1 seems a bit confusing to me for some reason.




回答2:


I make a point to do neither. I've found that code readability improves if you assign the tuple to a descriptive variable.

For instance:

for name in relative_names:
    print name

vs

for name in "Tyler", "Robert", "Marla", "Chloe", "Lou":
    print name



回答3:


I would always prefer:

>>> # Some setup
... some_values = 1, 'Hi', True,
>>> 
>>> # Style 3: named tuple
... for value in some_values:
...     print(value)
... 
1
Hi
True



回答4:


In this case explicit is better than implicit, the tuple should be obvious.

I think there are bigger fish to fry though :) Anybody will know what you are up to in either case, and it's a tiny change.



来源:https://stackoverflow.com/questions/6000291/best-style-for-iterating-over-a-small-number-of-items-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!