使用多个条件过滤字典列表

filter list of dictionaries using multiple conditions

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

简而言之,我希望输出的是字典中没有 'sell' 的那个名字 例如

没有卖单,所以输出应该只有'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