Getting an element from tuple of tuples in python
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Tuple value by key
号
我如何通过国家名称的代码来找到它,
1 2 3 4 5 6 7 8 9 10 | 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')) ) |
我有代码
您只需执行以下操作:
1 2 | countries_dict = dict(COUNTRIES) # Conversion to a dictionary mapping print countries_dict['AS'] |
这只是在国家缩写和国家名称之间创建一个映射。访问映射非常快:如果您进行多次查找,这可能是最快的方法,因为Python的字典查找非常高效。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 |
。
你不能。
要么
1 | [x[1] for x in COUNTRIES if x[0] == 'AS'][0] |
或
1 | filter(lambda x: x[0] == 'AS', COUNTRIES)[0][1] |
号
但这些仍然是"循环"。