Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个列表合并到一个以唯一值为键的字典中_Python_List_Dictionary - Fatal编程技术网

Python 将两个列表合并到一个以唯一值为键的字典中

Python 将两个列表合并到一个以唯一值为键的字典中,python,list,dictionary,Python,List,Dictionary,我有两个列表,都是同一个len: owner=["John","John","Mark","Bill","John","Mark"] restaurant_number=[0,2,3,6,9,10] 我想将其转化为一份口述,告知每位店主的餐厅编号: d={"John":[0,2,9],"Mark":[3,10],"Bill&q

我有两个列表,都是同一个len:

owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]
我想将其转化为一份口述,告知每位店主的餐厅编号:

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
有没有一种更像python的方法可以做到这一点?

像+这样的东西可以在这里工作:

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))
没有依赖关系

根据您的意见:

owner=["John","John","Mark","Bill","John","Mark"]
restaurant_number=[0,2,3,6,9,10]
准备收件人字典
res
,将空列表作为值,然后在不需要压缩的情况下填充它:

res = {own: [] for own in set(owner)}

for i, own in enumerate(owner):
  res[own].append(restaurant_number[i])
结果

print(res)
#=> {'Mark': [3, 10], 'Bill': [6], 'John': [0, 2, 9]}

这个问题经常被问(例如),但没有一个特别好的答案。多年来,我曾多次对此感到好奇,每次我都得出结论:不,没有更好的办法。也就是说,你可以用
defaultdict
之类的东西把一些边整圆,然后把输入压缩在一起,但是,在不影响big-O性能的情况下,您无法避免强制执行for循环。搜索重复项也很困难,因为很难简明而具体地描述问题陈述。@KarlKnechtel感谢您找到了重复项。这是我搜索的第一件事,因为我确信已经有了答案,但我无法找到它。我有一个被骗的锤子,但我不想在这里使用它。。。。
print(res)
#=> {'Mark': [3, 10], 'Bill': [6], 'John': [0, 2, 9]}