2015-09-10 61 views
0

我想結合以下兩個列表,但組合1a除外。python中既沒有也沒有聲明

a=[1,2,3,4,5,6,7,8,9] 
b=['a', 'b', 'c','d', 'e','f','g'] 
c=[] 

for i in a: 
    for j in b: 
     if i is not 1 and j is not'a': 
      c.append(str(i) + j) 

print c 

這排除了1和'a'的所有組合。我怎樣才能排除1a

+2

決不比較整數或'is'浮動。使用'=='和'!='。 –

+1

布爾代數101,德摩根定律。 – njzk2

回答

7

「i是1,j是'a'」的相反不是「我不是1,j不是'a'」。您還需要翻轉二元運算符。有關更多信息,請參見De Morgan's laws

另外,當比較值時,應該使用等號運算符==而不是is

if i is not 1 and j is not'a': 

更改爲:

if i != 1 or j != 'a': 
1

你想要的是

if not (i == 1 and j == 'a') 

,或者

if i != 1 or j != 'a' 
相關問題