从python中的元组元组中获取元素

时间:2012-01-05 09:44:12

标签: python tuples

  

可能重复:
  Tuple value by key

如何通过提供代码

来查找国家/地区名称
COUNTRIES = (
   ('AF', _(u'Afghanistan')),
   ('AX', _(u'\xc5land Islands')),
   ('AL', _(u'Albania')),
   ('DZ', _(u'Algeria')),
   ('AS', _(u'American Samoa')),
   ('AD', _(u'Andorra')),
   ('AO', _(u'Angola')),
   ('AI', _(u'Anguilla'))
)

我有代码AS,在COUNTRIES元组上没有使用forloop找到它的名字?

3 个答案:

答案 0 :(得分:23)

您可以这样做:

countries_dict = dict(COUNTRIES)  # Conversion to a dictionary mapping
print countries_dict['AS']

这只是创建了国家/地区缩写和国家/地区名称之间的映射。访问映射的速度非常快:如果你进行多次查找,这可能是最快的方法,因为Python的字典查找非常有效。

答案 1 :(得分:3)

COUNTRIES = (
   ('AF', (u'Afghanistan')),
   ('AX', (u'\xc5land Islands')),
   ('AL', (u'Albania')),
   ('DZ', (u'Algeria')),
   ('AS', (u'American Samoa')),
   ('AD', (u'Andorra')),
   ('AO', (u'Angola')),
   ('AI', (u'Anguilla'))
)

print (country for (code, country) in COUNTRIES if code=='AD').next()
#>>> Andorra

print next((country for (code, country) in COUNTRIES if code=='AD'), None)
#Andorra
print next((country for (code, country) in COUNTRIES if code=='Blah'), None)
#None

# If you want to do multiple lookups, the best is to make a dict:
d = dict(COUNTRIES)
print d['AD']
#>>> Andorra

答案 2 :(得分:1)

你不能。

无论

[x[1] for x in COUNTRIES if x[0] == 'AS'][0]

filter(lambda x: x[0] == 'AS', COUNTRIES)[0][1]

但这些仍然是“循环”。

相关问题