假设我有这样的数据:
filter_data = [
{'sender_id': 1, 'receiver_id': 2, 'order': 1},
{'sender_id': 2, 'receiver_id': 1, 'order': 3},
{'sender_id': 3, 'receiver_id': 2, 'order': 5},
{'sender_id': 2, 'receiver_id': 3, 'order': 2},
]
# there must be a better way to get max elements by reversed keys
# in list of dicts, but I think this whole another question
# so for now let this be this way.
def get_data():
qs_data = []
for data in filter_data:
for cmp_data in filter_data:
if data['sender_id'] == cmp_data['receiver_id'] and\
data['receiver_id'] == cmp_data['sender_id']:
if data['order'] > cmp_data['order']:
d = data
else:
d = cmp_data
if d not in qs_data:
qs_data.append(d)
return qs_data
期望的输出将是
^{2}$我的代码会过滤filter_data
,因此我将为sender_id
和receiver_id
获得最大值order
的项目列表,但对我来说receiver_id=1, sender_id=2
与{
所以我的问题是有没有更多的Python/更快的方法来做到这一点?或者是有人可以指出改进的方向。在
如果有人能给我起个头衔,我会很感激的。对不起,我的英语不好。在
我现在明白了吗?在
创建一个空字典来收集新的最高字典。我们遍历您的}的和,因为您说过这些顺序无关紧要。在
filter_data
,并检查sender_id
和{例如,它将遍历第一个字典并计算其}(总和为3)。因为我们还没有遇到}相加为3的字典,所以它被添加到我们的新字典中。在
receiver_id
和{sender_id
和{然而,下一本字典也有一个3的和。我们检查它的
order
值是否大于上一个字典。既然如此,它就覆盖了以前的字典。在然后打印新字典的值,因为键只包含}。在
sender_id
和{您可以使用字典,将发送方和接收方ID的
frozenset
映射到当前最高顺序的项。在然后,只需从字典中提取}
values()
,得到{或者收集所有项目,按发送方/接收方对分组,并使用列表理解和
^{pr2}$max
来获得顺序最高的项目:相关问题 更多 >
编程相关推荐