【问题标题】:Python. How to conveniently count the frequence of lists in a collection of listsPython。如何方便地计算列表集合中列表的频率
【发布时间】:2019-11-27 19:38:35
【问题描述】:

我有一个列表。

e.g. list_a = [[1,2,3], [2,3], [4,3,2], [2,3]]

我想把它们数成这样

[1,2,3]: 1
[2,3]: 2
[4,3,2]: 1

集合中有一个库计数器,但不适用于列表等不可散列的元素。目前,我只是尝试使用其他间接方式,例如将列表 [1,2,3] 转换为字符串“1_2_3”来做到这一点。有没有其他方法可以直接开启对列表的计数?

【问题讨论】:

  • 如果列表只包含整数转换为元组和应用计数器,否则排序如果元素是可排序的 + itertools.groupby。否则只是一个嵌套的 for 循环
  • @DanielMesejo 你还需要先排序
  • @roganjosh 你的意思是使用计数器吗?
  • Counter(map(tuple,list_a)) 给出:Counter({(1, 2, 3): 1, (2, 3): 2, (4, 3, 2): 1})
  • @DanielMesejo 我做到了...但现在在查看您的编辑之前可能有些事情我不知道

标签: python list counter


【解决方案1】:

这不是最漂亮的方法,但这是可行的:

list_a = [[1,2,3], [2,3], [4,3,2], [2,3]]
counts = {} 

for x in list_a: 
    counts.setdefault(tuple(x), list()).append(1) 
for a, b in counts.items(): 
    counts[a] = sum(b) 
print(counts) 
{(2, 3): 2, (4, 3, 2): 1, (1, 2, 3): 1}

【讨论】:

  • 为什么有两个 for 循环?您可以只检查密钥是否已经存在,然后添加 +=1 到它,0 默认值。然后你只迭代一次,节省大量内存
  • 因为这是我想到的第一个解决方案。正如我所说,绝对不是其他答案所示的最佳方法。
【解决方案2】:

完成这项工作的一种可能方法是使用dict

  1. 创建一个空字典
  2. 使用 for 循环遍历列表。
  3. 对于每个元素(迭代),检查字典是否包含它。
  4. 如果没有,请将其作为密钥保存在dict 中。该值将是发生计数器。
  5. 如果有,只需增加它的值。

可能的实现:

occurrence_dict = {}

for list in list_a:
    if (occurrence_dict.get(str(list), False)):
        occurence_dict[str(list)] += 1
    else:
        ocorrence_dict[str(list)] = 1

print(occurence_dict)

【讨论】:

    【解决方案3】:

    使用tuple 而不是list,您可以轻松实现它

    c = Counter(tuple(item) for item in list_a)
    # or
    c = Counter(map(tuple, list_a))
    
    # Counter({(2, 3): 2, (1, 2, 3): 1, (4, 3, 2): 1})
    # exactly what you expected
    (1, 2, 3) 1
    (2, 3) 2
    (4, 3, 2) 1
    

    【讨论】:

      【解决方案4】:

      方式 1

      通过可重复列表的索引

      list_a = [[1,2,3], [2,3], [4,3,2], [2,3], [1,2,3]]  # just add some  data
      
      # step 1
      dd = {i:v for i, v in enumerate(list_a)}
      print(dd)
      
      Out[1]:
      {0: [1, 2, 3], 1: [2, 3], 2: [4, 3, 2], 3: [2, 3], 4: [1, 2, 3]}
      
      # step 2
      tpl = [tuple(x for x,y in dd.items() if y == b) for a,b in dd.items()]
      print(tpl)
      
      Out[2]:
      [(0, 4), (1, 3), (2,), (1, 3), (0, 4)]  # here is the tuple of indexes of matching lists
      
      # step 3
      result = {tuple(list_a[a[0]]):len(a) for a in set(tpl)}
      print(result)
      
      Out[3]:
      {(4, 3, 2): 1, (2, 3): 2, (1, 2, 3): 2}
      

      方式 2

      通过将嵌套列表转换为元组

      {i:[tuple(a) for a in list_a].count(i) for i in [tuple(a) for a in list_a]}
      
      Out[1]:
      {(1, 2, 3): 2, (2, 3): 2, (4, 3, 2): 1}
      

      【讨论】:

        猜你喜欢
        • 2017-02-25
        • 2017-01-27
        • 2011-03-11
        • 2016-05-20
        • 1970-01-01
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多