您可以使用collections.defaultdict
:
创建字典后使用它只需 O(1) 查找即可找到“红色”或任何其他颜色的任何实例。
>>> myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for k,v in myList:
dic[k].append(v)
...
>>> dic['Red'][0] #first instance
'Tomato'
>>> dic['Red'][-1] #last instance
'Strawberry'
>>> dic["Yellow"][0] #first instance of Yellow
'Lemon'
在这里定义一个简单的函数来处理索引错误:
>>> def solve(n, color, dic):
try:
return dic[color][n]
except IndexError:
return "Error: {0} has only {1} instances".format(color,len(dic[color]))
...
>>> dic = defaultdict(list)
>>> for k,v in myList:
dic[k].append(v)
...
>>> solve(0, "Red", dic)
'Tomato'
>>> solve(-1, "Red", dic)
'Strawberry'
>>> solve(0, "Yellow", dic)
'Lemon'
>>> solve(1, "Yellow", dic)
'Error: Yellow has only 1 instances'