如何在 python 的两个列表中添加重复出现的元素

How to add repeating occurences of elements in two lists in python

我有

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]

这里,

 A=3, B=4 ,C=5, D =6, B=5. C=3

我想要一本像这样的字典,

time_per_screen{A:3,B:9,C:8,D:6}
filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
time_per_screen = {}
for a, b in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    time_per_screen[a] = b

编辑:您应该确保 2 个列表的长度相同...我将把它留给您。有一个名为 google 的好工具...它已经存在了一段时间 ;)

尝试这样做:

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
time_per_second = {}
for a, b in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    try:
        time_per_screen[a] += b
    except KeyError:
        time_per_screen[a] = b

如果字典中已经存在键值,这将添加键值,否则将创建一个新的键值对。

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    if not mydict.has_key(i):
        mydict[i]=j
    else:
        mydict[i]=j+mydict[i]

您需要添加 if else 以迭代添加 keys

或者干脆

filtered_symbolic_path = ['A', 'B', 'C', 'D', 'B', 'C']
filtered_symbolic_path_times = [ 3, 4, 5, 6, 5, 3]
mydict={}
for i,j in zip(filtered_symbolic_path,filtered_symbolic_path_times):
    mydict.setdefault(i,0)
    mydict[i]=j+mydict[i]

计数任务最好用 Counters 处理。创建一个计数器并继续将这些对附加到计数器。最后从计数器创建一个字典,这是你想要的输出。

示例代码

from collections import Counter
for p, t in zip(filtered_symbolic_path, filtered_symbolic_path_times):
    c.update({p:t})

示例输出

>>> dict(c)
{'A': 3, 'C': 8, 'B': 9, 'D': 6}