【发布时间】:2019-06-01 08:43:54
【问题描述】:
我有一个看起来像这样的列表(它是安然数据,因此是公开的,所以很确定我在这里没有违反任何规则):
{
'METTS MARK':{
'salary':365788,
'to_messages':807,
'deferral_payments':'NaN',
'total_payments':1061827,
'loan_advances':'NaN',
'bonus':600000,
'email_address':'mark.metts@enron.com',
'restricted_stock_deferred':'NaN',
'deferred_income':'NaN',
'total_stock_value':585062,
'expenses':94299,
'from_poi_to_this_person':38,
'exercised_stock_options':'NaN',
'from_messages':29,
'other':1740,
'from_this_person_to_poi':1,
'poi':False,
'long_term_incentive':'NaN',
'shared_receipt_with_poi':702,
'restricted_stock':585062,
'director_fees':'NaN'
},
'BAXTER JOHN C':{
'salary':267102,
'to_messages':'NaN',
'deferral_payments':1295738,
'total_payments':5634343,
'loan_advances':'NaN',
'bonus':1200000,
'email_address':'NaN',
'restricted_stock_deferred':'NaN',
'deferred_income':-1386055,
'total_stock_value':10623258,
'expenses':11200,
'from_poi_to_this_person':'NaN',
'exercised_stock_options':6680544,
'from_messages':'NaN',
'other':2660303,
'from_this_person_to_poi':'NaN',
'poi':False,
'long_term_incentive':1586055,
'shared_receipt_with_poi':'NaN',
'restricted_stock':3942714,
'director_fees':'NaN'
},
'ELLIOTT STEVEN':{
'salary':170941,
'to_messages':'NaN',
'deferral_payments':'NaN',
'total_payments':211725,
'loan_advances':'NaN',
'bonus':350000,
'email_address':'steven.elliott@enron.com',
'restricted_stock_deferred':'NaN',
'deferred_income':-400729,
'total_stock_value':6678735,
'expenses':78552,
'from_poi_to_this_person':'NaN',
'exercised_stock_options':4890344,
'from_messages':'NaN',
'other':12961,
'from_this_person_to_poi':'NaN',
'poi':False,
'long_term_incentive':'NaN',
'shared_receipt_with_poi':'NaN',
'restricted_stock':1788391,
'director_fees':'NaN'
}
}
我正在尝试列出所有exercised_stock_options 值,然后我想找到非NaN 值并执行最大值/最小值。
我这样做了,但我得到了一个不正确的答案,我不知道为什么:
eso = []
for k,v in data_dict.items():
# name.append[str(k)]
eso.append(v['exercised_stock_options'])
# Remove NaN values in list
eso = [x for x in eso if str(x) != 'NaN']
print(eso)
sorted(eso)
print(eso[0])
print(eso[-1])
但后来我看到了这个答案,它是正确的,但我看不出我做错了什么?
stock = []
for i in data_dict:
if (data_dict[i]["exercised_stock_options"]=='NaN'):
pass
else:
stock.append(float(data_dict[i]["exercised_stock_options"]))
ma = max(stock)
mi = min(stock)
print ("Exercised stock options maximum: ", ma, " minimum: ", mi)
【问题讨论】:
-
sorted不会更改列表,它只是返回它的排序版本。将sorted(eso)替换为eso.sort(),这将对eso进行破坏性排序。 -
或者
eso = sorted(eso) -
另一点,您的列表是字符串,而您展示的解决方案是将值转换为浮动。不确定这样的排序是否会影响结果。
标签: python list dictionary max min