【问题标题】:How to add repeating occurences of elements in two lists in python如何在python的两个列表中添加重复出现的元素
【发布时间】:2015-06-11 05:11:42
【问题描述】:

我有

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}

【问题讨论】:

  • 它是一个简单的字典格式,在许多地方被解释为无数次..+1 关闭

标签: python python-2.7 logic


【解决方案1】:

尝试这样做:

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

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

【讨论】:

  • Bare except 可以捕获比预期更多的异常。最好提供异常的名称(在这种情况下为KeyError)。或使用@vks 回答中的setdefault 并完全避免捕获异常。
【解决方案2】:
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]

【讨论】:

  • 命名变量dict shadows 内置dict(字典构造函数),请选择其他名称(例如mydict)。最好写i not in mydict 而不是not mydict.has_key(i),后者在Python 3 中不再可用。 mydict[i] = j + mydict[i] 可以缩写为 mydict[i] += j
【解决方案3】:
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 的简洁工具……它已经存在了一段时间了;)

【讨论】:

  • OP 想要对相同字母下的数字求和,但您的代码不这样做。
  • @AudriusKažukauskas 你是对的,我错过了。
【解决方案4】:

计数任务最好使用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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多