【问题标题】:Count sublists with the same values in a list计算列表中具有相同值的子列表
【发布时间】:2021-05-03 18:35:42
【问题描述】:

如何计算列表中具有相同值(顺序无关紧要)的子列表?

我试过了:

from collections import Counter

Input = [
    [
        'Test123', 'heyhey123', 'another_unique_value',
    ],
    [
        'Test123', 'heyhey123', 'another_unique_value',
    ],
    [
        'heyhey123',
    ],
    [
        'Test123', 'heyhey123',
    ],
    [
        'another_unique_value', 'heyhey123', 'Test123'
    ]
]

Counter(str(e) for e in li)

Output:

Counter({
    "['Test123', 'heyhey123', 'another_unique_value']": 2},
    "['heyhey123']": 1},
    "['Test123', 'heyhey123']": 1},
    "['another_unique_value', 'heyhey123', 'Test123']": 1},
)

显然,它会根据列表中的值进行排序。如何计算顺序无关紧要的子列表?

我想要的输出是:

Counter({
    "['Test123', 'heyhey123', 'another_unique_value']": 3},
    "['heyhey123']": 1},
    "['Test123', 'heyhey123']": 1},
)

【问题讨论】:

  • 使用set(e) 而不是str(e)
  • @Barmar 你必须使用tuple(set(e)) - 集合是不可散列的。
  • 另外,如果值可以在一个子列表中出现两次,您可以使用tuple(sorted(e))。
  • @CDJB 宾果游戏!。 tuple(set(e)) 可能不起作用,因为未定义集合元素的顺序。
  • @CDJB 成功了!

标签: python pandas counter


【解决方案1】:

你可以替换

Counter(str(e) for e in li)

与

Counter(tuple(sorted(e)) for e in li)

给出输出:

Counter({('Test123', 'another_unique_value', 'heyhey123'): 3,
         ('heyhey123',): 1,
         ('Test123', 'heyhey123'): 1})

另一种选择是使用set(e) 来忽略列表中元素的顺序,但这有忽略重复的缺点——['Test123', 'heyhey123', 'another_unique_value'] 将被视为与['Test123', 'heyhey123', 'another_unique_value', 'another_unique_value'] 相同——此外,当从不可散列的set 转换为包含在Counter 中,不能保证相同的顺序。

【讨论】:

    【解决方案2】:

    我认为你很接近。

    Counter(str(set(e)) for e in Input)
    返回

    Counter({"{'heyhey123', 'Test123', 'another_unique_value'}": 3,
         "{'heyhey123'}": 1,
         "{'heyhey123', 'Test123'}": 1})
    

    我相信这与您正在寻找的几乎相同:)

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多