是否有蟒蛇這兩個語句之間的差異:圓括號對Python中的'或'運算符有什麼影響?
if tag == ('/event' or '/organization' or '/business'):
和
if tag == '/event' or '/organization' or '/business':
是否有蟒蛇這兩個語句之間的差異:圓括號對Python中的'或'運算符有什麼影響?
if tag == ('/event' or '/organization' or '/business'):
和
if tag == '/event' or '/organization' or '/business':
他們都錯了。你需要的是:
if tag == '/event' or tag == '/organization' or tag == '/business':
或:
if tag in ['/event', '/organization', '/business']:
我也不一定會給你想要的方式。你會怎樣想的是:
if tag in ['/event', '/organization', '/business']:
的妥善解決是
if tag in ('/event', '/organization', '/business'):
它不僅採用了in
操作很適合這個目的,但也使用一個元組(不可變的)所以python的解釋器優化它比一個(可變的)列表更好。表示元組比列表更快
基準:
In [1]: import timeit
In [2]: t1 = timeit.Timer('"b" in ("a", "b", "c")')
In [3]: t2 = timeit.Timer('"b" in ["a", "b", "c"]')
In [4]: t1.timeit(number=10000000)
Out[4]: 0.7639172077178955
In [5]: t2.timeit(number=10000000)
Out[5]: 2.240161895751953
你有基準表明一個元組更快嗎? – interjay 2011-04-26 13:30:21
@interjay,這是我運行的一個小測試(似乎使用元組更快) >>> timeit.timeit('a = 9; x =(1,2,3,4,5); a in x') 0.23711281741111634 >>> timeit。timeit('a = 9; x = [1,2,3,4,5]; a in x') 0.4927707292406467 – sateesh 2011-04-26 13:39:43
我會說從3.2開始,更快的方法是{1,2,3}中的x請參閱http ://docs.python.org/dev/whatsnew/3.2.html#optimizations – 2011-04-26 13:41:03
('/event' or '/organization' or '/business')
被評估爲'/event'
,從而第一件事是等價於if tag == '/event':
tag == '/event' or '/organization' or '/business'
相當於(tag == '/event') or '/organization'
。
你真正想要的是:
if tag in ('/event', '/organization', '/business'):
第一個是相同的if tag == 'event'
。第二個與if tag == '/event' or True or True
相同,它始終爲真。
用元組替換該列表。 – orlp 2011-04-26 13:29:23
@nightcracker:爲什麼? – interjay 2011-04-26 13:31:08
@nightcracker:我不同意。對我來說,元組表明了排序。 – 2011-04-26 13:32:36