python - 将两个列表合并到一个字典中,以唯一值作为键
问题描述
我有这两个列表,具有相同的 len:
owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]
我想把它变成一个通知每个所有者的 restaurant_number 的字典:
d={"John":[0,2,9],"Mark":[3,10],"Bill":[6]}
我可以用丑陋的方式做到这一点:
unique=set(owner)
dict={}
for i in unique:
restaurants=[]
for k in range(len(owner)):
if owner[k] == i:restaurants.append(restaurant_number[k])
dict[i]=restaurants
有没有更蟒蛇的方式来做到这一点?
解决方案
像defaultdict + zip这样的东西可以在这里工作:
from collections import defaultdict
d = defaultdict(list)
owner = ["John", "John", "Mark", "Bill", "John", "Mark"]
restaurant_number = [0, 2, 3, 6, 9, 10]
for o, n in zip(owner, restaurant_number):
d[o].append(n)
print(dict(d))
{'John': [0, 2, 9], 'Mark': [3, 10], 'Bill': [6]}
推荐阅读
- python - For循环函数只返回相同的值
- html - 使用 HTML/CSS 在新行中显示图像
- kubernetes - GKE 负载均衡器服务上的最大端口数
- excel - 如果在同一工作表中满足条件,如何复制列
- swift - 如何在不使用 MasksToBound = False 的情况下向 TableView 添加阴影
- xml - 如何为记录导出和格式化 XML?
- python - Python return 在之前的函数中触发 else
- python - Python Tkinter time.sleep 与 selenium webdriver 循环等效?
- c++ - 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)c++ clion
- regex - 在使用 Perl 和 AutoHotKey 的 RegEx 方面需要帮助