在Python列表中计算唯一列表

时间:2019-03-07 10:27:04

标签: python list count

如何统计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

谢谢。

3 个答案:

答案 0 :(得分:4)

如果您不关心输出的格式,一种选择是将子列表转到tuples,然后使用collections.Counter

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

tuples

输出

from collections import Counter

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

答案 1 :(得分:0)

{
    "error": {
        "code": "TimeZoneNotSupportedException",
        "message": "A valid TimeZone value must be specified. The following TimeZone value is not supported: ''.",
        "innerError": {
            "request-id": "4833ea1a-3371-4d3e-b28e-193fec18f723",
            "date": "2019-03-07T11:01:36"
        }
    }
}

输出:

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)

答案 2 :(得分:0)

没有依赖性的详细选项:

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}