我开始学习python已经很久了,但我真的很想深入研究它.并努力挖掘.所以这是一个我已经研究了一段时间但尚未破解的任务:
我给出了嵌套字典和列表的混合组合(让我们称之为" 组合 "),我需要实现允许访问的函数嵌套元素作为对象属性,也以某种方式将组合元素视为可迭代.这应该是这样的:
combination = {
'item1': 3.14,
'item2': 42,
'items': [
'text text text',
{
'field1': 'a',
'field2': 'b',
},
{
'field1': 'c',
'field2': 'd',
},
]
}
def function(combination):
...
Run Code Online (Sandbox Code Playgroud)
这
list(function(combination).items.field1)
将给予:['a', 'c'],
list(function(combination).item1)并将给予:[3.14].
编辑正如@FM所提到的,我错过了处理非字典元素的描述:
list(function(combination).items[0])>>>['text text text']
我尝试实现一个类(对Marc的称赞)来帮助我:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
Run Code Online (Sandbox Code Playgroud)
然后在使用它的功能等return Struct(**combination)
虽然是非常漂亮的,这仅仅是第一步所期望的结果.
但是,随着下一步需要更深入,它会压倒我,我不能自己做.
因此,我请求你的帮助.
迈克尔.
python ×1