【发布时间】:2018-08-08 05:35:46
【问题描述】:
我正在用这种格式在 python 中迭代一个复杂的列表:
[
{
<parent id>: [
<child id>,
<child id>
],
<parent id>: [
<child id>
]
},
{
<parent id>: [
<child id>,
<child id>,
<child id>
],
<parent id>: [
<child id>
]
}
]
列表将包含 dict 作为元素。这些字典有<parent id> 的键和<child id> 列表的值
不同的dict中可以有相同的<parent id>,但<child id>只能属于一个<parent id>。一个例子是这样的:
[
{
2: [1, 5],
3: [3, 7],
4: [6]
},
{
1: [2, 4, 8],
4: [6]
}
]
父 id 4 在两个 dict 元素中,但所有子 id 对于父 id 都是唯一的。
现在我将这个数据结构作为输入进行迭代,因为我想确保满足所有孩子对父 ID 唯一的条件。这是我的代码:
def check_format(self, mapping):
# mapping is the data structure
unique_parent_list = []
child_list = []
for x in range(0, 2):
for parent in mapping[x].keys():
if parent not in unique_parent_list:
unique_parent_list.append(parent)
for child in mapping[x][parent]:
child_list.append(child)
if len(child_list) > len(set(child_list)):
return 'Condition not met'
else:
return 'Condition met'
这可行,但我不喜欢它是 O^4 复杂性或类似的东西。有没有办法简化或编码以获得更好的性能?
【问题讨论】:
-
请为您的变量添加更多描述性名称。
key->parent和y->child例如。
标签: python for-loop nested-loops