2015-12-02 22 views
2

我有兩個城市和國家的名單。如何將城市與僅使用列表的國家相關聯,而不是在Python中使用字典?

List1=['Athens', 'Sidney'] 

List2=['Greece', 'Australia'] 

c=raw_ input('Enter a city: ') 

雅典是在希臘,悉尼是在澳大利亞。

如何測試Sidney是否在澳大利亞使用列表而不是字典?

+2

但更好的方法是保持字典。創建國家/地區名稱鍵併爲其指定一個城市列表作爲值 – NSNoob

+0

您可以對列表進行壓縮以創建元組,或者您可以對列表編制索引,但這僅適用於1:1關係,因此這不是一種可擴展的方法。 –

回答

2

這是你可以做什麼:

result = [country for city,country in zip(List1,List2) if city == c] 
if result: 
    print('This city is in {}'.format(result[0])) 
else: 
    print('City not found') 
0

zip兩個列表,形成了字典和檢查悉尼關鍵!

myHash=dict(zip(List1, List2)) 
myHash.has_key("Sidney") 

打印True如果存在其他False

1

我同意其他人:接近這一點的最好辦法是使用一本字典。但是,如果你仍然堅持不讓兩個單獨的列表:

cities = ['Athens', 'Sidney'] 
countries = ['Greece', 'Australia'] 
user_city = raw_input('Enter a city: ') 

try: 
    country = countries[cities.index(user_city)] 
    print user_city, 'is in', country 
except ValueError: 
    print user_city, 'is not in the list of cities' 

  • 表達cities.index(user_city)將返回索引位置user_citycities列表中。但是,如果user_city不在列表中,則會發生ValueError異常。這就是爲什麼我在下面處理它。
  • 與該索引,我現在可以看一下國家和打印出來的結果
相關問題