Python:anoth中的数据结构

2024-05-29 06:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

在Perl中,可以执行以下操作:

my $data->[texts}->{text1} = "hey";
print data->{texts}->{text1};

它会打印“嘿”。它就像另一个数据结构中的一个数据结构(数组)。。。你知道吗

显然,这在Python中是可能的:

data = { 'jack': 4098, 'sape': 4139 }
print data['jack'];

但是我想要类似于:data['texts']['text1']的东西,就像在Perl中一样。你知道吗

我需要能够很容易地移除和添加到这个结构中。。。你知道吗

救命啊?你知道吗


Tags: 数据结构datamy数组结构perlprintjack
2条回答

您在这里使用^{} object。它可以存储任何类型的元素,包括另一个dict对象。你知道吗

也就是说,您可以初始化data,如下所示:

data = {'jack': {'age': 20, 
                 'gender': 'M'
                }, 

        'sape': {'age': 35, 
                 'gender': 'F'
                } 
       }

然后参考它的内部值:

print(data['jack']['age'] # prints "20"

下面的代码描述了所需的数据结构

代码:

rec = {'name': {'first': 'Bob', 'last': 'Smith'},
                  'job': ['dev', 'mgr'],
                  'age': 40.5}

rec['name'] # 'Name' is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

rec['name']['last'] # Index the nested dictionary
'Smith'

 rec['job'] # 'Job' is a nested list
['dev', 'mgr']

 rec['job'][-1] # Index the nested list
'mgr'

 rec['job'].append('janitor') # Expand Bob's job description in-place

 rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':
'Bob'}}

参考 https://bdhacker.wordpress.com/2010/02/27/python-tutorial-dictionaries-key-value-pair-maps-basics/

相关问题 更多 >

    热门问题