[英]Find an element in a list with tuple in Python
我有一些复杂的数据,想找到带有关键元组的特定元素。 target tuple 与key有点不同,因为它有一个id属性。 所以我不能在 target 中使用key 。
那么在这种情况下实现智能搜索的最佳方法是什么?
targets = [
{"id": 0, "X": (), "Y": (), "Z": () },
{"id": 1, "X": (1,), "Y": (5,), "Z": ()},
{"id": 2, "X": (1,), "Y": (5, 7), "Z": ()},
{"id": 3, "X": (2,), "Y": (5, 7), "Z": (1,)},
{"id": 4, "X": (1, 2), "Y": (5, 7), "Z": (1,)},
{"id": 5, "X": (1, 2), "Y": (5, 7), "Z": (1,3)},
]
key = {"X": (1,), "Y": (5, 7), "Z": ()}
我想实现find方法来提取预期的插槽,如下所示。
In []: find(targets, key)
Out[]: {'id': 2, 'X': (1,), 'Y': (5, 7), 'Z': ()}
如果键值对必须完全匹配,您可以使用Dictionary 视图对象将键值对视为集合。 你想找到一个严格的子集:
def find(targets, key):
for target in targets:
if key.items() < target.items():
return target
这只会找到第一个匹配项。
你可以把它变成一个单行:
next((target for target in targets if key.items() < target.items()), None)
如果必须生成所有匹配项,则可以在上述方法中将return
替换为yield
以将其转换为生成器,或者您可以使用列表推导式:
[target for target in targets if key.items() < target.items()]
以上使用 Python 3 语法。 在 Python 2 中,字典视图可通过特殊的.viewkeys()
、 .viewvalues()
和.viewitems()
方法获得,因此在view
添加方法名称:
def find(targets, key):
# Python 2 version
for target in targets:
if key.viewitems() < target.viewitems():
return target
演示(在 Python 3 上):
>>> targets = [
... {"id": 0, "X": (), "Y": (), "Z": () },
... {"id": 1, "X": (1,), "Y": (5,), "Z": ()},
... {"id": 2, "X": (1,), "Y": (5, 7), "Z": ()},
... {"id": 3, "X": (2,), "Y": (5, 7), "Z": (1,)},
... {"id": 4, "X": (1, 2), "Y": (5, 7), "Z": (1,)},
... {"id": 5, "X": (1, 2), "Y": (5, 7), "Z": (1,3)},
... ]
>>> key = {"X": (1,), "Y": (5, 7), "Z": ()}
>>> def find(targets, key):
... for target in targets:
... if key.items() < target.items():
... return target
...
>>> find(targets, key)
{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}
>>> next((target for target in targets if key.items() < target.items()), None)
{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}
>>> [target for target in targets if key.items() < target.items()]
[{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.