我试图得到一个dict中的属性计数,其中poi==true。我已经包括了一个C示例作为参考,后面是我的python代码。你知道吗
用Python做这件事的正确方法是什么?你知道吗
C#:
enron_data.where(x => x.poi == true).count()
在Python中:
i = 0
for key,value in enron_data.items():
if value["poi"]:
i = i + 1
print i
安然数据样本:
{'METTS MARK': {'salary': 365788, 'to_messages': 807, 'deferral_payments': 'NaN', 'total_payments': 1061827, 'exercised_stock_options': 'NaN', 'bonus': 600000, 'restricted_stock': 585062, 'shared_receipt_with_poi': 702, 'restricted_stock_deferred': 'NaN', 'total_stock_value': 585062, 'expenses': 94299, 'loan_advances': 'NaN', 'from_messages': 29, 'other': 1740, 'from_this_person_to_poi': 1, 'poi': False, 'director_fees': 'NaN', 'deferred_income': 'NaN', 'long_term_incentive': 'NaN', 'email_address': 'mark.metts@enron.com', 'from_poi_to_this_person': 38}}
您可以这样使用
iter_items()
函数:或者
我可能会这样做,假设
poi
总是True
或False
。你知道吗enron_data.values()
提供一个迭代器,它将返回字典的值。我们对钥匙不感兴趣。对于每一个,我们得到'poi'
键的值。那是什么我会给你的。假设
v['poi']
总是True
或False
,我使用int()
将其转换为整数。int(True)
是1
,int(False)
是0
。所以,如果我运行这个,我将得到一个1
和0
的列表。然后我sum
整个列表来获得1
的计数(即True
s),使用sum
内置。我删除了[
和]
,因为我只是在列表上迭代,而不是索引它或任何东西。你知道吗我想到了另一个选择。你知道吗
假设您有一个字典,其中每个值都有一个
poi
键(您的问题暗示了这一点):然后将
True
条目数相加:相关问题 更多 >
编程相关推荐