迭代Python中少量项目的最佳风格? [英] Best style for iterating over a small number of items in Python?
问题描述
我只是在阅读有关python的演示文稿,并且我注意到作者错过了元组的圆括号以进行迭代,因此令我惊讶的是我可能倾向于将它们留在里面。读取 PEP-8 并没有给出明确的答案,但我没有希望不作任何讨论就退缩旧的显性胜于隐性;所以...
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 ...
您更喜欢哪个?您认为在这两个等效的for语句中哪一个更适合python(将讨论限制为在for语句中使用)。
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
>>>
推荐答案
我会选择样式2 ,因为您实际上可以理解要迭代的内容:
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)
样式1出于某种原因,这让我有些困惑。
Style 1 seems a bit confusing to me for some reason.
这篇关于迭代Python中少量项目的最佳风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!