2017-04-11 52 views
0

建立的Python:找到確切的單詞

我有以下的字典,

d={'City':['Paris', 'Berlin','Rome', 'London']} 

和下面的一個元素的列表,

address=['Bedford Road, London NW7'] 


問題

我想檢查一個城市是否在地址中。


嘗試到目前爲止

(1)

for x in d['City']: 
    if x in address: 
    print('yes') 
    else: 
    print('no') 

只打印no

(2)

for x in d['City']: 
    r = re.compile(x) 
    newlist = list(filter(r.match, address)) 

給出TypeError: 'str' object is not callable。從this answer得到這個似乎是應該解決這個問題,但錯誤沒有幫助。

我該怎麼辦?

回答

2

您的解決方案#1實際上是相當接近,但它不工作,因爲address是字符串列表,而不是一個字符串本身。

所以,它會完全正常工作,如果你只是把名單addressaddress[0]的第一要素。

或者,你可以試試這個:

>>> any(i in address[0] for i in d['City']) 
True 

對於代碼片段,您可以使用:

if any(i in address[0] for i in d['City']): 
    print 'Yes' 
else: 
    print 'No' 
+0

謝謝。就是這樣。切換到你光滑的替代雖然;) – LucSpan

0

如果不增加列表的大小:

for x in d['City']: 
    if x in address[0]: 
     print('yes') 
    else: 
     print('no') 
+0

你不需要使用拆分,你可以刪除它,它會繼續w掃。 – eyllanesc

+0

你是對的,編輯於 – lordingtar

+0

爲了改善你的帖子,你可以改善你的解釋。 – eyllanesc

1

由於您的地址是一個元素的列表,你應該檢查address[0]而不是address

for x in d['City']: 
    if x in address[0]: 
     print('yes') 
    else: 
     print('no') 
+0

謝謝。你是對的。 – LucSpan