简体   繁体   English

将名称与嵌套列表相关联

[英]associating names with nested lists

I'm stuck on how I can append additional information to the lowest level of a list leaf. 我被困在如何将附加信息附加到列表叶的最低级别上。 I'm currently using: 我目前正在使用:

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

fruit_detail = []

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

Which gives me: 这给了我:

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

Later on, I'm attempting to append more details to the list: 稍后,我尝试将更多详细信息添加到列表中:

fruit_detail[tomato].append('red')

And I receive the error 我收到错误

NameError: name 'tomato' is not defined

Is it possible to achieve what I'm trying? 是否有可能实现我正在尝试的目标?

You should use a dictionary instead: 您应该改用字典

fruit_detail = {}

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

Now you can address each list by the fruit name: 现在,您可以按水果名称寻址每个列表:

>>> 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']

Your code was using unnecessary extra lists, but to do the same with just a simple list: 您的代码使用了不必要的额外列表,但只需一个简单的列表即可完成此操作:

fruit_detail = []

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

you'd have to scan through the whole list first to even find the matching list: 您必须先扫描整个列表才能找到匹配的列表:

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

which is not nearly as efficient or easy to work with. 效率不高或不容易使用。 The more items you add, the longer it takes to search. 您添加的项目越多,搜索时间就越长。 Dictionaries on the other hand are much, much more efficient in finding values you associated with a key. 另一方面,字典在查找与键关联的值时要高效得多。

For more information, see the Dictionaries section of the Python tutorial . 有关更多信息,请参见Python教程的“ 词典”部分

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM