我有一个python字典对象,看起来有点像这样:
shutdown()
现在对于每个'sign'键,我想计算每个值出现的次数。
HazelcastInstance
然而,这会打印字典中出现'符号'的次数,而不是获取[{"house": 4, "sign": "Aquarius"},
{"house": 2, "sign": "Sagittarius"},
{"house": 8, "sign": "Gemini"},
{"house": 3, "sign": "Capricorn"},
{"house": 2, "sign": "Sagittarius"},
{"house": 3, "sign": "Capricorn"},
{"house": 10, "sign": "Leo"},
{"house": 4, "sign": "Aquarius"},
{"house": 10, "sign": "Leo"},
{"house": 1, "sign": "Scorpio"}]
的值并计算特定值出现的次数。
例如,我想看到的输出是:
def predominant_sign(data):
signs = [k['sign'] for k in data if k.get('sign')]
print len(signs)
等等。我应该改变什么来获得所需的输出?
答案 0 :(得分:14)
使用collections.Counter
及其most_common
method:
from collections import Counter
def predominant_sign(data):
signs = Counter(k['sign'] for k in data if k.get('sign'))
for sign, count in signs.most_common():
print(sign, count)
答案 1 :(得分:4)
您可以使用collections.Counter
模块,使用简单的生成器表达式,例如
>>> from collections import Counter
>>> Counter(k['sign'] for k in data if k.get('sign'))
Counter({'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1})
这将为您提供一个字典,其中signs
为关键字,其出现次数为值。
您可以使用普通字典执行相同的操作,例如
>>> result = {}
>>> for k in data:
... if 'sign' in k:
... result[k['sign']] = result.get(k['sign'], 0) + 1
>>> result
{'Sagittarius': 2, 'Capricorn': 2, 'Aquarius': 2, 'Leo': 2, 'Scorpio': 1, 'Gemini': 1}
dictionary.get
方法接受第二个参数,如果在字典中找不到该键,则该参数将是返回的默认值。因此,如果当前符号不在result
中,则会改为0
。
答案 2 :(得分:0)
def counter(my_list):
my_list = sorted(my_list)
first_val, *all_val = my_list
p_index = my_list.index(first_val)
my_counter = {}
for item in all_val:
c_index = my_list.index(item)
diff = abs(c_index-p_index)
p_index = c_index
my_counter[first_val] = diff
first_val = item
c_index = my_list.index(item)
diff = len(my_list) - c_index
my_counter[first_val] = diff
return my_counter
>>> counter([list(i.values())[1] for i in my_list])
{'Aquarius': 2,
'Capricorn': 2,
'Gemini': 1,
'Leo': 2,
'Sagittarius': 2,
'Scorpio': 1}