将名称与嵌套列表相关联

时间:2014-03-19 20:28:51

标签: python list data-structures

我一直坚持如何将附加信息附加到列表叶的最低级别。我目前正在使用:

fruits = ['tomato', 'apple', 'watermelon']

fruit_detail = []

for fruit in fruits:
    fruit_detail.append([[fruit, [fruit + ' is delicious']]])

这给了我:

[[['tomato', ['tomato is delicious']]], [['apple', ['apple is delicious']]], [['watermelon', ['watermelon is delicious']]]]

稍后,我试图在列表中添加更多详细信息:

fruit_detail[tomato].append('red')

我收到错误

NameError: name 'tomato' is not defined

是否有可能实现我的目标?

1 个答案:

答案 0 :(得分:6)

您应该使用词典

fruit_detail = {}

for fruit in fruits:
    fruit_detail[fruit] = [fruit + ' is delicious']

现在,您可以通过水果名称来解决每个列表:

>>> fruits = ['tomato', 'apple', 'watermelon']
>>> fruit_detail = {}
>>> for fruit in fruits:
...     fruit_detail[fruit] = [fruit + ' is delicious']
... 
>>> fruit_detail['tomato']
['tomato is delicious']
>>> fruit_detail['tomato'].append('red')
>>> fruit_detail['tomato']
['tomato is delicious', 'red']

您的代码使用了不必要的额外列表,但仅使用一个简单的列表执行相同操作:

fruit_detail = []

for fruit in fruits:
    fruit_detail.append([fruit, [fruit + ' is delicious']])

您必须首先扫描整个列表才能找到匹配列表:

for fruit_name, fruit_info in fruit_detail:
    if fruit_name == 'tomato':
        fruit_info.append('red')

效率不高或不易使用。您添加的项目越多,搜索所需的时间就越长。另一方面,字典在查找与键相关联的值时效率更高,效率更高。

有关详细信息,请参阅Dictionaries section of the Python tutorial