Python - 如何计算出现次数

时间:2014-11-18 01:54:01

标签: python python-jira

我使用jira-python库查询jira中的数据。我从jira获取了我需要的数据,但处理数据一直给我带来问题。

我希望计算从查询中返回的所有组件的出现次数。例如,我的查询将返回结果:

Component A
Component B
Component A
Component C

我正在寻找的结果如下:

Component A, 2
Component B, 1
Component C, 1

以下是我当前代码的片段:

search = 'jira query'
issues = jira.search_issues(search, maxResults=100)
for issue in issues:
    [c.name for c in issue.fields.components]

从这里开始,我试图计算并总结c.name

sum(1 for c.name in issue.fields.components)

然而,这不会产生正确的结果,因为我会得到结果,比如计算每个结果的字符出现次数。

非常感谢任何见解/帮助

3 个答案:

答案 0 :(得分:0)

将名称的列表/生成器表达式传递给collections.Counter对象。

答案 1 :(得分:0)

import collections
>>> my_result = '''Component A
... Component B
... Component A
... Component C'''
>>> my_result = my_result.split('\n')   # if they are saperated by newline
>>> my_result
['Component A', 'Component B', 'Component A', 'Component C']
>>> my_result_count = collections.Counter(my_result)
>>> my_result_count
Counter({'Component A': 2, 'Component B': 1, 'Component C': 1})
>>> for x in sorted(my_result_count.keys()):
...     print x + ", " + str(my_result_count[x])
... 
Component A, 2
Component B, 1
Component C, 1

collections.Counter将返回字典及其出现的字典

答案 2 :(得分:0)

浏览问题和组件并计算它们。

# dictionary where we will hold results of counting of componets
count_result = {}

# we search for issues we are interested in
issues = jira.search_issues("project = PROJECT_KEY", maxResults=100)
for issue in issues:
    # in case there is more components we iterate through them all
    # and count them in count_result dictionary
    for component in [c.name for c in issue.fields.components]:
        if count_result.get(component):
            # if component already exists in count_result dictionary
            count_result[component] += 1
        else:
            # if component doesn't exists in count_result dictionary
            count_result[component] = 1

# print out of result
for name,value in count_result.items():
    print "%s, %d" % (name, value)