在Python中计算列表中的唯一列表

2024-04-23 11:03:27 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中计算列表中的每个列表? 我特别想知道他们有多少共同点。你知道吗

示例:

list=[["a", "b", "c"], ["a", "A", "b"], ["B", "c", "C"],["a", "b", "c"]]

想要的输出:

 value            counts
["a", "b", "c"]   2
["a", "A", "b"]   1
["B", "c", "C"]   1

谢谢。你知道吗


Tags: 示例列表valuelistcounts共同点
3条回答

无依赖项的详细选项:

lst = [["a", "b", "c"], ["a", "A", "b"], ["B", "c", "C"],["a", "b", "c"]]

res = {}
for array in lst:
    res.setdefault(tuple(array), list()).append(1)

它创建一个以子列表为键的字典,每次匹配时都附加1。然后用和变换关键点:

for k,v in res.items():
  res[k] = sum(v)
  # print(k, res[k])

取消对打印行的注释:

# ('a', 'b', 'c') 2
# ('a', 'A', 'b') 1
# ('B', 'c', 'C') 1

res现在是:

res #=> {('a', 'b', 'c'): 2, ('a', 'A', 'b'): 1, ('B', 'c', 'C'): 1}

如果您不关心输出的格式,一个选项是将子列表转换为tuples,然后使用^{}。你知道吗

这背后的原因是Counter返回一个哈希表,并且只有不可变的类型才是可哈希的,因此一种解决方法是将子列表强制转换为tuples,而tuples是不可变的,与列表不同:

from collections import Counter

Counter([tuple(i) for i in l])

输出

Counter({('a', 'b', 'c'): 2, ('a', 'A', 'b'): 1, ('B', 'c', 'C'): 1})
from collections import Counter
list1 = [["a", "b", "c"], ["a", "A", "b"], ["B", "c", "C"],["a", "b", "c"]]
dictionary = Counter([tuple(i) for i in list1])
dd = pd.DataFrame(data={'list': list(dictionary.keys()),'count': list(dictionary.values())})
print(dd)

输出:

        list  count
0  (a, b, c)      2
1  (a, A, b)      1
2  (B, c, C)      1

相关问题 更多 >