【问题标题】:Adding together the contents of a second list whenever an item appears in a first list每当项目出现在第一个列表中时,将第二个列表的内容加在一起
【发布时间】:2016-02-02 18:05:00
【问题描述】:

我有两个列表:标签和权重(它们排列在一起:权重[i] 用于标签[i])。标签可以出现多次。所以,我要做的是将每个标签的所有权重加在一起,得到每个标签的总权重。

列表如下所示

tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]

我想要得到的是这样的:

tags = ['alternative', 'indie', 'jam rock', 'punk']
weights =[175, 70, 45, 50]

我尝试过使用各种循环,但我不知道如何正确地得到它。我一直在使用.remove(i),它将摆脱重复的标签,但这就是我所能做的。

任何想法如何做到这一点?

【问题讨论】:

  • 请通过提供输入和预期输出以及您迄今为止所做的尝试,让您的问题更清楚!
  • 模式:使用计数器或zip() 遍历weight 列表。使用标签作为键和权重列表作为值构建一个字典。
  • 好的,我已经编辑澄清了!
  • 这里有个提示:你可以使用defaultdict

标签: python list addition


【解决方案1】:

使用字典(如果您想简化代码,则使用默认字典)。

tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
weights = [100, 20, 45, 50, 75, 50]
d = {}
for tag, weight in zip(tags, weights):
    if tag in d:
        d[tag] += weight
    else:
        d[tag] = weight

new_tags = [tag for tag in sorted(d)] #if you want it in alphabetical order
new_weights = [d[tag] for tag in new_tags]
print new_tags
print new_weights

【讨论】:

    【解决方案2】:

    作为替代方法,您可以使用 Python 的 Counter,如下所示:

    from collections import Counter
    
    tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
    weights = [100, 20, 45, 50, 75, 50]
    totals = Counter()
    
    for t, w in zip(tags, weights):
        totals[t] += w
    
    print totals
    

    这将显示以下输出:

    Counter({'alternative': 175, 'indie': 70, 'punk': 50, 'jam rock': 45})
    

    totals 然后可以像普通字典一样使用,例如print totals['indie'] 将返回 70

    【讨论】:

      【解决方案3】:

      我建议在这种情况下使用字典,因为并行列表很容易错位。这是一个使用defaultdict的例子,就像cmets中建议的铁拳一样。

      from collections import defaultdict
      tagDict = defaultdict(int)
      tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
      weights = [100, 20, 45, 50, 75, 50]
      
      for i in range(len(tags)):
          tagDict[tags[i]] += weights[i]
      
      print tagDict
      

      【讨论】:

        【解决方案4】:

        使用来自collectionsdefaultdict

        >>> tags = ['alternative', 'indie', 'jam rock', 'indie', 'alternative', 'punk']
        >>> weights = [100, 20, 45, 50, 75, 50]
        >>> 
        >>> 
        >>> from collections import defaultdict
        >>> 
        >>> d = defaultdict(int)
        >>> 
        >>> for k,v in zip(tags, weights):
                d[k] += v
        
        >>> d
        defaultdict(<class 'int'>, {'jam rock': 45, 'punk': 50, 'alternative': 175, 'indie': 70})
        >>> 
        >>> d['alternative']
        175
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-12-22
          • 1970-01-01
          • 1970-01-01
          • 2021-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-18
          相关资源
          最近更新 更多