像我这样的Python初学者的挑战,我需要创建包含浮点数值列表字典的对象。我尝试了这个流程,对象似乎是在线创建的,但是代码停在我试图将更多值附加到已经创建的对象的行上,告诉我:
AttributeError:'float'对象没有属性'append'
这是我用于此任务的一段代码:
class Wimp(object):
def __init__(self, mass, definitions):
self.mass = mass
self.dN_dx = {}
for definition in definitions:
self.dN_dx[definition] = []
print definition, "added"
print "Wimp of mass", self.mass, "created."
wimp_data = {}
i=0
for mass in nu_e_mass:
if mass == nu_e_mass[i+1]:
#Saving the columns into arrays
if mass not in wimp_data:
wimp_data[mass] = Wimp(mass, definitions)
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]] = float(nu_e[j][i])
else:
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(nu_e[j][i])
#print mass, "Same mass", nu_e_mass[i+1]
if i < (len(nu_e_mass)-2):
i = i+1
else:
#Integrating the columns and storing into Wimp class
#print mass, "Skipping to next mass", i, nu_e_mass[i+1]
i = i+1
如果有人能够发现错误,那就太好了,因为我现在几个小时都在看这段代码..
答案 0 :(得分:3)
好像你在第一个for循环中将元素定义为float而不是list:
wimp_data[mass].dN_dx[definitions[j]] = float(nu_e[j][i])
很自然地,你不能在第二个中附加它。也许你打算把它作为一个包含单个浮点数的列表:
wimp_data[mass].dN_dx[definitions[j]] = [float(nu_e[j][i])]
答案 1 :(得分:2)
wimp_data [mass] .dN_dx [definitions [j]] 是一个浮点数,你创建了它。你可能想要的是:
wimp_data[mass].dN_dx[definitions[j]] = []
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(float(nu_e[j][i]))
为映射分配一个列表。
BTW:整个if / else结构的更紧凑版本可能是:
if mass not in wimp_data:
wimp_data[mass].dN_dx[definitions[j]] = []
wimp_data[mass] = Wimp(mass, definitions)
for j in range(1, len(definitions)):
wimp_data[mass].dN_dx[definitions[j]].append(nu_e[j][i])