2012-03-26 42 views
1
if ('0' or '13' or '26' or '39') in user and accumulator + 11 <= 21: 
    accumulator += 11 
    print 'ADDING 11!!!!!' 
elif ('0' or '13' or '26' or '39') in user: 
    accumulator + 1 
    print 'ADDING 1' 

這是脫離整個程序的上下文。我有print語句在那裏爲調試目的,但是,我有if語句確定0,13,26或39是否在列表useraccumulator + 11不會超過21我有試過沒有括號和單引號,有什麼建議?如何測試if語句中的數字是否在列表中?

回答

0
accumulator + 1 

應該

accumulator += 1 
+0

因爲他的if語句是錯誤的,所以甚至從未達到該行。他知道這是因爲他包含了'print'語句。 – agf 2012-03-26 16:16:20

2

如果你檢查整數而含有ASCII字符串的數字,是的,離開落單引號。

你的意思是

if any(x in user for x in ('0', '13', '26', '39')) and accumulator + 11 <= 21: 

這做什麼它說 - 它檢查是否有這些字符串(或數字,如果你刪除引號)都在名單user

您需要對elif進行相同的更改。

而且,你的意思是

accumulator += 1 

,而不是

accumulator + 1 
0

正如@agf提到,使用any多個or和多個and使用all將是應對自然的方式可以使用另一種方法使用組

例如

給出

user1=['1','13','25'] 
and 
user2=['0','1','13','14','26','27','39'] 

if ('0' or '13' or '26' or '39') in user1

其通常寫爲

any(x in user1 for x in ['0' , '13' , '26' , '39']) 

也可以寫爲

not set(['0' , '13' , '26' , '39']).isdisjoint(user1) 
or 
len(set(['0' , '13' , '26' , '39']).intersection(user1))>0 

並且類似地

if ('0' and '13' and '26' and '39') in user2 

其通常寫爲

all(x in user2 for x in ['0' , '13' , '26' , '39']) 

也可以寫爲

len(set(['0' , '13' , '26' , '39']).difference(user2)) == 0 

所以回到你的問題,用交集,我們可以寫成

if not set(['0' , '13' , '26' , '39']).isdisjoint(user1) and accumulator + 11 <= 21: 
    accumulator += 11 
    print 'ADDING 11!!!!!' 
elif ('0' or '13' or '26' or '39') in user: 
    accumulator += 1 
    print 'ADDING 1' 
+0

一般情況下,不要將'len'對零進行測試,只需要使用空'set'評估爲'False'的事實。 – agf 2012-03-26 16:56:38

0

一些其他的答案是好的,但他們可能不明白新的人到Python。這裏是更清晰的東西(但不是pythonic,可能比較慢的情況下,無查找號碼在用戶,等等......是的,我知道)。

lookup_numbers = ['0', '13', '26', '39'] 
num_found = False 
for lookup_number in lookup_numbers: 
    if lookup_number in user: 
    num_found = True 
    break 

if num_found: 
    if ((accumulator + 11) <= 21): 
    accumulator += 11 
    else: 
    accumulator += 1 

注意:如果您的用戶列表包含字符串,然後繼續爲每個條目的報價在 lookup_numbers。它如果包含整數,則刪除引號。

+0

邏輯不等價。即使沒有任何數字匹配,這裏的'else'子句也會被達到,如果它們匹配但是累加器測試沒有匹配,他似乎只想達到它。另外,您的累加器測試會多次發生,這是不必要的。 – agf 2012-03-26 16:53:58

+0

@agf謝謝。我修好了它。 – 2012-03-26 17:16:44