根据条件python计数项目数量的最佳方法

发布于 2025-02-06 04:22:14 字数 594 浏览 0 评论 0原文

嗨,大家好,我有多种条件可以检查一系列对象:

我的示例数组是这样的

[{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"}]

,因为这些记录将在10000中,我想以最好的方式计算这些记录的总和。

目前这样做,

   view_count = [element for element in user_record if element['type'] == "viw"  ]
   edit_count = [element for element in user_record if element['type'] == "edit"]
   crt_count = [element for element in user_record if element['type'] =="crt"]

   and then len(crt_count) ,len(edit_count) ,len(view_count) 

对我来说似乎有点贵。请指南我可以优化的方式吗?

我可以在此列表中使用第二个问题或条件吗?

Hi guys I have multiple conditions to check on a array of objects for example :

My sample array is like this

[{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"}]

as these records will be in 10000's I want to calculate total sum of these in best way possible .

Currently doing like this

   view_count = [element for element in user_record if element['type'] == "viw"  ]
   edit_count = [element for element in user_record if element['type'] == "edit"]
   crt_count = [element for element in user_record if element['type'] =="crt"]

   and then len(crt_count) ,len(edit_count) ,len(view_count) 

which seems to me a little expensive . kindly guide can I do it in optimize way ?

and 2nd question can I use OR condition with if in this list comprehension ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

孤城病女 2025-02-13 04:22:14

使用:

d={}
for dct in sample_arr:
    key = dct['type']
    if d.get(key) is None:
        d[key] = 0
    d[key] += 1

dict(d)
 {'viw': 1, 'edit': 1, 'crt': 1}

或使用defaultDict

from collections import defaultdict  
e = defaultdict(int)
for dct in sample_arr:
    e[dct['type']] +=1
dict(e)
 {'viw': 1, 'edit': 1, 'crt': 1}

use:

d={}
for dct in sample_arr:
    key = dct['type']
    if d.get(key) is None:
        d[key] = 0
    d[key] += 1

dict(d)
 {'viw': 1, 'edit': 1, 'crt': 1}

or use defaultdict:

from collections import defaultdict  
e = defaultdict(int)
for dct in sample_arr:
    e[dct['type']] +=1
dict(e)
 {'viw': 1, 'edit': 1, 'crt': 1}
我不是你的备胎 2025-02-13 04:22:14

来计算其值

result = {}
for element in user_record:
   try:
        result[element["type"]] += 1
   except KeyError: 
        result[element["type"]] = 1

只需将每个“类型”收集到字典键中,然后用@not机器人的评论 :
“基本上相同想法的另一种方法:”

collections.Counter(map(operator.itemgetter('type'), my_list))

第二个问题:答案是是,您可以使用这样的方法:

edit_count = [element for element in user_record if element['type'] == "edit" or element['type'] == 'viw']

Just collect each of the 'types' into a dictionary key and count them with it's value

result = {}
for element in user_record:
   try:
        result[element["type"]] += 1
   except KeyError: 
        result[element["type"]] = 1

per comment from @Not A Robot :
"another way for essentially the same idea:"

collections.Counter(map(operator.itemgetter('type'), my_list))

Second Question: Answer is yes you can use or like this:

edit_count = [element for element in user_record if element['type'] == "edit" or element['type'] == 'viw']
℉絮湮 2025-02-13 04:22:14

如果您关心避免多次迭代,只需通过一次迭代来计算:

sample_arr = [{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"}]

view_count, edit_count, crt_count = 0, 0, 0

for d in sample_arr:
    if d['type'] == 'viw':
        view_count += 1
    elif d['type'] == 'edit':
        edit_count += 1
    elif d['type'] == 'crt':
        crt_count += 1

If you're concerned with avoiding multiple iterations, just count through one iteration:

sample_arr = [{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"}]

view_count, edit_count, crt_count = 0, 0, 0

for d in sample_arr:
    if d['type'] == 'viw':
        view_count += 1
    elif d['type'] == 'edit':
        edit_count += 1
    elif d['type'] == 'crt':
        crt_count += 1
空城旧梦 2025-02-13 04:22:14

不使用循环的另一个选项(但使用额外的内存):

import pandas as pd

arr = [{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"},
       {"id":2 , "type":"viw"},{"id":2 , "type":"edit"},{"id":2 , "type":"crt"}]

df = pd.DataFrame(arr)
res = df['type'].value_counts().to_dict()

>>> res
{'viw': 2, 'edit': 2, 'crt': 2}

another option without using for loop (but using extra memory):

import pandas as pd

arr = [{"id":1 , "type":"viw"},{"id":1 , "type":"edit"},{"id":1 , "type":"crt"},
       {"id":2 , "type":"viw"},{"id":2 , "type":"edit"},{"id":2 , "type":"crt"}]

df = pd.DataFrame(arr)
res = df['type'].value_counts().to_dict()

>>> res
{'viw': 2, 'edit': 2, 'crt': 2}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文