gpt4 book ai didi

python - 计算列表中具有相同值的子列表

转载 作者:行者123 更新时间:2023-12-04 17:18:52 25 4
gpt4 key购买 nike

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

我试过这个:

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},
)

最佳答案

可以替换

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 中,不保证相同的顺序。

关于python - 计算列表中具有相同值的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67374115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com