Python:在对象列表中获取两个 bool 属性频率的最有效方法?

标签 python list properties frequency

我有一个 User 对象,有两个 bool 属性,如下所示:

class User(object):
  def __init__(self, a, b):
    self.a = a  # Always a bool
    self.b = b  # Always a bool

我有一个这些对象的列表,称为 user_list,我想获得一个频率计数,了解有多少对象具有 a == True、a == False、b == True,以及b == 假。

我最初的方法是使用 collections.Counter,但这需要遍历列表两次:

a_count = collections.Counter(u.a for u in user_list)
b_count = collections.Counter(u.b for u in user_list)
print a_count[True], a_count[False], b_count[True], b_count[False]

我也考虑过只使用 4 个计数器,但这很丑而且感觉不像 pythonic:

a_true_count = 0
a_false_count = 0
b_true_count = 0
b_false_count = 0
for u in user_list:
  if u.a:
    a_true_count += 1
  else:
    a_false_count += 1
  if u.b:
    b_true_count += 1
  else:
    a_false_count += 1
print a_true_count, a_false_count, b_true_count, b_false_count

有没有更有效的方法来做到这一点?输出可以是任何东西:4 个单独的变量、一个带有值的字典、一个列表、元组等等,只要它包含这 4 个值即可。

提前致谢!

最佳答案

我认为使用 collections.Counter 是正确的想法,只需以更通用的方式使用单个 Counter 和单个循环即可:

from collections import Counter

user_list = [User(True, False), User(False, True), User(True, True), User(False, False)]
user_attr_count = Counter()

for user in user_list:
    user_attr_count['a_%s' % user.a] += 1
    user_attr_count['b_%s' % user.b] += 1

print user_attr_count
# Counter({'b_False': 2, 'a_True': 2, 'b_True': 2, 'a_False': 2})

关于Python:在对象列表中获取两个 bool 属性频率的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15560389/

相关文章:

python - 在 Python 中自动创建列表

java - apache-commons-config PropertiesConfiguration : comments after last property is lost

Javascript:拆分为多个变量

python - odoo 12 中many2many 字段的更改行为

python - Python 中 nltk.sentiment.vader 的错误消息

list - 使用 Haskell 将列表拆分为长度为 2^0、2^1、...、2^N 的元组列表

Python删除列表的重叠

properties - 如何在 C++/CLI 接口(interface)中声明默认索引属性

python - 如何动态地将属性添加到类中?

python - 使用 pandas 随机生成数据集