根据条件python计数项目数量的最佳方法
嗨,大家好,我有多种条件可以检查一系列对象:
我的示例数组是这样的
[{"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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用:
或使用
defaultDict
:use:
or use
defaultdict
:来计算其值
只需将每个“类型”收集到字典键中,然后用@not机器人的评论 :
“基本上相同想法的另一种方法:”
第二个问题:答案是是,您可以使用
或
这样的方法:Just collect each of the 'types' into a dictionary key and count them with it's value
per comment from @Not A Robot :
"another way for essentially the same idea:"
Second Question: Answer is yes you can use
or
like this:如果您关心避免多次迭代,只需通过一次迭代来计算:
If you're concerned with avoiding multiple iterations, just count through one iteration:
不使用循环的另一个选项(但使用额外的内存):
another option without using
for
loop (but using extra memory):