从元组的元组中获取元素

16 投票
3 回答
15982 浏览
提问于 2025-04-17 09:35

可能重复的问题:
通过键获取元组值

我怎么通过国家代码找到国家名称呢?

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 这个元组中找到它的名称?

3 个回答

1

你不能这样做。

要么

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

要么

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

但这些仍然是“循环”。

4
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

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得更简单易懂。

30

你可以这样做:

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

这段代码简单地建立了一个国家缩写和国家名称之间的对应关系。访问这个对应关系非常快:如果你需要查找多个国家,这种方法可能是最快的,因为Python的字典查找效率很高。

撰写回答