使用多个条件筛选字典列表



我想根据名称和顺序过滤列表数据。输出应如下所示:

  • 过滤后,它应该给出'abc'的名称,因为在每个具有name = 'abc'的字典中,所有顺序都是'buy'
  • 不是'xyz''dfg',因为有些订单中有'sell'

简而言之,我希望输出应该是在任何字典中都没有'sell'的名称例如

  • CCD_ 8,以及
  • {'name': 'abc', 'order':'Buy', 'quantity': 255252}

没有销售订单,所以输出应该只有'abc'

输入

data = [
{'name': 'abc', 'order':'Buy', 'quantity': 25252},
{'name': 'xyz', 'order':'Buy', 'quantity': 4444},
{'name': 'dfg', 'order':'sell', 'quantity': 254242252},
{'name': 'xyz', 'order':'sell', 'quantity': 25224252},
{'name': 'abc', 'order':'Buy', 'quantity': 24424},
{'name': 'dfg', 'order':'sell', 'quantity': 2424},
{'name': 'abc', 'order':'Buy', 'quantity': 255252},
]

所需输出

'abc'

这是我能想到的最简单的方法

sell_list = []
res = []
# This loop will check for all the items that have order = sell
for i in data:
if i['order'] == 'sell' and i['name'] not in sell_list:
sell_list.append(i['name'])
for i in data:
# Checking if the item has order = buy and check if it already have order = sell 
if i['order'] == 'Buy' and i['name'] not in sell_list and i['name'] not in res:
res.append(i['name'])

print(res)

如果data是您的列表,则:

sell_set = {d["name"] for d in data if d["order"] == "sell"}
print(
*{
d["name"]
for d in data
if d["order"] == "Buy" and not d["name"] in sell_set
}
)

打印:

abc

最新更新