在Python if语句中使用列表和元组 [英] Using lists and tuples in Python if statements
问题描述
我想知道是否有充分的理由在python if
语句中偏爱列表而不是元组,反之亦然.因此,以下内容在功能上是等效的,但就性能和编码样式而言,它们在其他方面还是比较可取的,或者这没关系吗?
I'm wondering whether there are any good reasons to prefer a list over a tuple or vice versa in python if
statments. So the following are functionally equivalent but is one preferable to the other in terms of performance and coding style or does it not matter?
if x in (1,2,3):
foo()
if x in [1,2,3]:
foo()
我似乎已经习惯了使用元组的习惯,如果有2或3个值和更长的列表,我想是因为根据我的经验,元组往往很短并且列出的很长,但这似乎有点武断,而且可能不必要地不一致.
I seem to have gotten into the habit of using tuples if there are 2 or 3 values and lists for anything longer, I think because in my experience tuples tend to be short and lists long, but this seems a bit arbitrary and probably needlessly inconsistent.
我会对人们能给出的一个例子比另一个例子更好的例子感兴趣.
I'd be interested in any examples people can give of where one would be better than the other.
欢呼声
推荐答案
tuple
的初始化(至少在CPython中)产生的字节码比list
少-但这实际上无需担心.我相信成员资格测试几乎相同(尽管未测试).
The initialisation of a tuple
(at least in CPython) produces less bytecode than a list
- but it's really nothing to worry about. I believe membership testing is pretty much the same (although not tested it).
对于纯成员资格测试,查找语义是相同的.从Python 2.7开始,编写起来要好得多(并暗示它仅是成员资格测试):
For purely membership testing the lookup semantics are the same. From Python 2.7 onwards, it's much nicer to write (and adds an implication that it's membership testing only):
if x in {1, 2, 3}:
pass # do something
在此之前:
if x in set([1,2,3]):
pass # do something
看起来有点糊涂...
just looked a little kludgy...
这篇关于在Python if语句中使用列表和元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!