在Python中從元組的元組中獲取元素

2024-05-19 17:03:08 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
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就可以找到它的名称?


Tags: key代码名称byvalueas国家ax
3条回答

你不能

或者

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

或者

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

但这些仍然是“循环”。

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

你可以简单地做:

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

这只会在国家缩写和国家名称之间创建一个映射。访问映射非常快:如果进行多次查找,这可能是最快的方法,因为Python的字典查找非常高效。

相关问题 更多 >