简体   繁体   English

计算python中多维数组中唯一字符串的数量

[英]Count the number of unique strings in a multidimensional array in python

I'm trying to count the number of unique strings in the second value of a multidimensional array. 我正在尝试在多维数组的第二个值中计算唯一字符串的数量。

My current code is: 我当前的代码是:

>>> a=[['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
>>> from collections import Counter
>>> result=Counter(a[1]);
>>> result
Counter({'2a': 1, '2b': 1, '2c': 1})

But, I want the output to be this: 但是,我希望输出是这样的:

Counter({'1b': 1, '2b': 1, '3b': 1})

Counting the second value in each list, rather than the three values from the second list. 计算每个列表中的第二个值,而不是第二个列表中的三个值。

I realize that Counter(a[1]) is wrong, but I'm not sure how to do it the way I want. 我意识到Counter(a[1])是错误的,但是我不确定如何按照自己的方式进行。

To count in the second "column", try this: 要计算第二个“列”,请尝试以下操作:

a = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
from collections import Counter
result = Counter(zip(*a)[1])
print result

Output: 输出:

Counter({'3b': 1, '1b': 1, '2b': 1})

Should be a bit quicker than using zip: 应该比使用zip快一点:

from collections import Counter

a = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
result = Counter(lst[1] for lst in a)
print(result)

gives

Counter({'3b': 1, '1b': 1, '2b': 1})

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

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