我想根据名称和顺序过滤列表数据。输出应如下所示:
'abc'
的名字,因为在每个有 'buy'
的字典中所有的订单都是 name = 'abc'
。'xyz'
和 'dfg'
,因为有些订单中包含 'sell'
。简而言之,我希望输出应该是在任何字典中都没有 'sell'
的名称
例如。
{'name': 'abc', 'order':'Buy', 'quantity': 25252},{'name': 'abc', 'order':'Buy', 'quantity': 24424}
,
和{'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'
答案 0 :(得分:0)
这是我能想到的最简单的方法
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)
答案 1 :(得分:0)
如果 def download_file(url):
# prefere with when exceptions are expected
with open(url.split("=")[-1] + ".pdf", 'wb') as fp:
delay = 5
max_retries = 3
for _ in range(max_retries):
try:
req = urlopen(url)
CHUNK = 20480
chunk = req.read(CHUNK)
fp.write(chunk)
break # do not loop after a successfull download...
except urllib.error.URLError:
time.sleep(delay)
delay *= 2
else: # signal an abort if download was not possible
print(f"Failed for {url} after {max_retries} attempt")
# or if you want to abort the script
# raise Exception(f"Failed for {url} after {max_retries} attempt")
是您的列表,则:
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
}
)