简体   繁体   English

如何制作分层列表python

[英]How do I make hierarchical lists python

I'm trying to create hierarchy lists python in python. 我正在尝试在python中创建层次结构列表python。 For example, There are several states. 例如,有几种状态。 In each state there are several counties, in each county they are several cities. 每个州有几个县,每个县有几个城市。 Then I would like be able to call those. 然后,我可以打电话给那些人。 I've tried creating list and appending lists to those list but I can't get to that to work. 我尝试创建列表并将列表追加到那些列表,但是我无法正常工作。 It also gets really messy. 它也变得非常混乱。 Thanks 谢谢

I just found this example: 我刚刚找到了这个例子:

tree = [
    ['Food', [
         ['Fruit', [
               ['Red', ['Cherry', 'Strawberry']],
               ['Yellow', ['Banana']],
         ]],
         ['Meat', [
               ['Beef', 'Pork']
         ]],
    ]],
]

Now my question would just be, is this the best way? 现在我的问题就是,这是最好的方法吗? how to call specific things? 如何称呼特定的事物? If I use... 如果我用...

print tree[0]

it will give me everything. 它会给我一切。 When I try 当我尝试

print tree[0[1]]

I get a type TypeError: 'int" object has no attribute '__getitem_' Thanks 我收到TypeError类型的错误:“ int”对象没有属性“ __getitem_”,谢谢

The direct answer to your question is that the list was likely created correctly, but you are not accessing it correctly. 您问题的直接答案是该列表可能是正确创建的,但是您没有正确访问它。

You access the nested lists like this: 您可以像这样访问嵌套列表:

tree[0][1]...

not like this 不像这样

tree[0[1[..]]]

However, you should use a dictionary, not a list. 但是,您应该使用字典,而不是列表。 It will make your look ups much more simple and they will be more efficient as well. 这将使您的查找更加简单,并且查找效率也会更高。

If you are interested in finding out how the dictionaries work. 如果您有兴趣了解字典的工作方式。 Google the term 'Associative array'. Google称为“关联数组”。 They are also known as hashes or hash tables. 它们也称为哈希表或哈希表。

Also, rather than using the term hierarchical the term multi-dimensional is more common. 此外,而不是使用期限分级术语多维是比较常见的。

eg this: 例如:

mylist=[
        [...],
        [...],
        .
        . 
       ]

Is a 2D list 是二维列表

Dictionaries are the way to go. 字典是必经之路。

d = {'food': 
        {'fruit':
            {'color':
                {'red': ['Cherry', 'Strawberry']},
                {'yellow': ['Banana']},
            },
        },
        {'meat': ['Beef', 'Pork']}
    }

Now you can do: 现在您可以执行以下操作:

for item in d['food']['fruit']['color']['red']:
    print(item)
# Cherry
# Strawberry

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

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