天平评估物体的硬度 函数应返回一个字典,将这样的列表中的对象分为四类。
答案 0 :(得分:0)
> import numpy as np
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)
。/
dict
输出
def func(ls):
dict_ = {'soft':[], 'medium':[],'hard':[], 'very hard':[]}
for i in ls:
# print(i)
if i[1] >= 1 and i[1] <=3:
dict_['soft'].append(i[0])
elif i[1] >= 3.1 and i[1] <= 5:
dict_['medium'].append(i[0])
elif i[1] >= 5.1 and i[1] <=8:
dict_['hard'].append(i[0])
elif i[1] >= 8.1 and i[1] <=10:
dict_['very hard'].append(i[0])
return dict_
print(func(rocks))
答案 1 :(得分:-1)
dict comprehension
和setdefault
方法:rocks = [('talc', 1), ('lead', 1.5), ('copper', 3), \
('nickel', 4), ('silicon', 6.5), ('emerald', 7.5),\
('boron', 9.5), ('diamond', 10)]
aa = {}
bb = {aa.setdefault("soft",[]).append(k) if 1 <= v <= 3 \
else aa.setdefault("medium",[]).append(k) if 3.1 <= v <= 5 \
else aa.setdefault("hard",[]).append(k) if 5.1 <= v <= 8 \
else aa.setdefault("very hard",[]).append(k) \
for k, v in rocks}
print (aa)
# Result--> {'soft': ['talc', 'lead', 'copper'], 'medium': ['nickel'], 'hard': ['silicon', 'emerald'], 'very hard': ['boron', 'diamond']}
我希望它甚至可以帮助您了解setdefault的用法。 :)