简体   繁体   English

如何计算Python列表中多个唯一出现的唯一事件?

[英]How to count multiple unique occurrences of unique occurrences in Python list?

Let's say I have a 2D list in Python: 假设我在Python中有一个2D列表:

mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]

In this case my "keys" would be the first element of each array ("A" or "B") and my "values" would be the second element ("X" or "Y"). 在这种情况下,我的“键”将是每个数组的第一个元素(“A”或“B”),而我的“值”将是第二个元素(“X”或“Y”)。 At the end of my consolidation the output should consolidate the keys and count the unique occurrences of values present for each key, ie something like: 在我合并结束时,输出应该合并密钥并计算每个密钥的唯一出现值,例如:

# Output
# {"A":{"X":2, "Y":2}, "B":{"X":2, "Y":1}}

I am trying to use Python's itertools.groupby, but to no avail. 我试图使用Python的itertools.groupby,但无济于事。 Something similar to this question . 类似这个问题的东西。 If you have a better method, let me know. 如果你有更好的方法,请告诉我。

Thanks! 谢谢!

I think the easiest way to do this would be with Counter and defaultdict: 我认为最简单的方法是使用Counter和defaultdict:

from collections import defaultdict, Counter

output = defaultdict(Counter)
for a, b in mylist:
    output[a][b] += 1

L3viathan's answer seems to be better. L3viathan的答案似乎更好。 However, this is another approach: 但是,这是另一种方法:

mylist = [["A", "X"],["A", "X"],["A", "Y"],["B", "X"],["B", "X"],["A", "Y"]]

dictionary = {"A": {"X": 0, "Y": 0}, "B": {"X": 0, "Y": 0}}
for x in mylist:
    dictionary[x[0]][x[1]] += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM