[英]Create nested list in dictionary without duplicates in the list
I'm doing a db query as such select fruits from warehouse
.我正在做一个数据库查询,例如
select fruits from warehouse
。 The goal is to create a dictionary with the fruits in each warehouse:目标是为每个仓库中的水果创建一个字典:
{13: [apple, orange, grapes], 14: [banana, pineapple], 20: [strawberry, avocado, blueberry]}
Any fruits that are present in several warehouses I want to remove altogether and I want to print an error message about them.我想完全删除几个仓库中存在的任何水果,我想打印有关它们的错误消息。 I got a solution that works but it requires several steps:
我得到了一个有效的解决方案,但它需要几个步骤:
fruits = set()
duplicates = set()
stock = {}
tmp = []
for warehouse in warehouses:
for row in results:
if row[0] in fruits
print row[0] + " is a duplicate"
duplicates.add(row[0])
else
fruits.add(row[0])
tmp.append(row[0])
stock[warehouse] = tmp
tmp = []
final_result = {}
#Remove duplicates
for warehouse,fruits in stock.iteritems():
final_result[warehouse] = []
for fruit in fruits:
if fruit not in duplicates:
final_result[warehouse].append(fruit)
I like to use dict/list comprehension where I can but that seems ruled out here and the whole approach looks a bit cumbersome, is there a better/cleaner way to achieve the same result?我喜欢尽可能使用 dict/list comprehension,但这似乎被排除在这里,整个方法看起来有点麻烦,有没有更好/更干净的方法来实现相同的结果?
Yes, there is, and in fact it can be done with comprehensions:是的,有,而且实际上可以通过理解来完成:
stock = {}
for warehouse in warehouses:
stock[warehouse] = []
for row in results:
stock[warehouse].append(row[0])
fruit_list = [fruit for warehouse in stock.values() for fruit in warehouse]
duplicates = {fruit for fruit in set(fruit_list) if fruit_list.count(fruit) > 1}
for fruit in duplicates:
print(fruit + " is a duplicate")
final_result = {warehouse:[fruit for fruit in fruits if fruit not in duplicates] for warehouse,fruits in stock.items()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.