2015-12-02 21 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异常。这就是为什么我在下面处理它。
  • 与该索引,我现在可以看一下国家和打印出来的结果
相关问题