简体   繁体   English

Python-如何计算对象内部数字的出现?

[英]Python - How to count occurrences of a number inside of an object?

I need to count the number of occurrences of a number in a object. 我需要计算一个对象中数字出现的次数。 Not sure how to do it. 不知道该怎么做。

I can access to the values in this way: 我可以通过以下方式访问值:

>>> formset_sample.forms[0]._raw_value('type')
>>> '1'
>>> formset_sample.forms[1]._raw_value('type')
>>> '2'
>>> formset_sample.forms[2]._raw_value('type')
>>> '2'

This object has len() = 3: 该对象的len()= 3:

>>> len(formset_sample.forms)
>>> 3

How can I obtain the occurrences of the number 2? 如何获得数字2的出现? The number '2' have exactly two occurences in this case. 在这种情况下,数字“ 2”恰好有两次出现。

Some clues? 一些线索?

Best Regards, 最好的祝福,

It's not clear to me what you want to achieve. 我不清楚您想要实现什么。 But maybe the map function helps you: 但是也许map功能可以帮助您:

 values = map(lambda x: x._raw_value('type'), formset_sample.forms)
 # alternate Syntax:
 values = [form._raw_value('type') for form in formset_sample.forms]
 print values

should give you the array 应该给你数组

 ['1', '2', '2']

which you could feed into a Counter : 您可以将其输入Counter

from collections import Counter
print Counter(values)

should be something like 应该是这样的

{ '1': 1, '2': 2 }

So if you want to put it all in one line: 因此,如果您想将所有内容放在一行中:

Counter([form._raw_value('type') for form in formset_sample.forms])["2"]

This should give you a list of numbers and count the number of 2s: 这应该给您一个数字列表并计算2s的数量:

l = [ f._raw_value('type') for f in formset_sample.forms ]
l.count('2') # I am assuming 2 is a string, or
l.count(2)   # if the number is stored as an integer

Now you can use l to sort, slice etc. 现在您可以使用l进行排序,切片等。

this will produce a dictionary with the different types as keys and number of occurences as values: 这将产生一个字典,其字典的不同类型为键,出现次数为值:

import defaultdict
d = defaultdict(int)
for rv in formset_sample.forms:
  d[rv._raw_value_('type')] += 1
a = {1:1, 2:1, 3:2}
print a.values().count(1)
count = sum(f._raw_value('type') == '2' for f in formset_sample.forms)

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

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