3 回答

TA贡献1880条经验 获得超4个赞
您应该避免在Python中按索引进行修改
>>> content2 = [-0.112272999846, -0.0172778364044, 0, 0.0987861891257,
0.143225416783, 0.0616318333661, 0.99985834, 0.362754457762, 0.103690909138,
0.0767353098528, 0.0605534405723, 0.0, -0.105599793882, -0.0193182826135,
0.040838960163]
>>> [float(x) if x else None for x in content2]
[-0.112272999846, -0.0172778364044, None, 0.0987861891257, 0.143225416783, 0.0616318333661, 0.99985834, 0.362754457762, 0.103690909138, 0.0767353098528, 0.0605534405723, None, -0.105599793882, -0.0193182826135, 0.040838960163]
要content2更改此列表理解的结果,请执行以下操作:
content2[:] = [float(x) if x else None for x in content2]
您的代码无效,原因是:
range((content2)-1)
你想减去1从list。此外,range端点是排他性的(它上升到端点- 1,您将1再次从中减去),因此您的意思是range(len(content2))
您对代码的这种修改有效:
for i in range(len(content2)):
if content2[i] == 0.0:
content2[i] = None
最好使用intPython中的s等于0评估为false的隐式事实,因此这同样可以正常工作:
for i in range(len(content2)):
if not content2[i]:
content2[i] = None
您也可以习惯于对列表和元组执行此操作,而不是if len(x) == 0按照PEP-8的建议进行检查
我建议的清单理解是:
content2[:] = [float(x) if x else None for x in content2]
在语义上等同于
res = []
for x in content2:
if x: # x is not empty (0.0)
res.append(float(x))
else:
res.append(None)
content2[:] = res # replaces items in content2 with those from res

TA贡献1851条经验 获得超4个赞
您应该在此处使用列表理解:
>>> content2[:] = [x if x!= 0.0 else None for x in content2]
>>> import pprint
>>> pprint.pprint(content2)
[-0.112272999846,
-0.0172778364044,
None,
0.0987861891257,
0.143225416783,
0.0616318333661,
0.99985834,
0.362754457762,
0.103690909138,
0.0767353098528,
0.0605534405723,
None,
-0.105599793882,
-0.0193182826135,
0.040838960163]

TA贡献1830条经验 获得超3个赞
稍微修改您的代码即可获得理想的结果:
for i in range(len(content2)):
if content2[i]==0:
content2[i] = None
在您的代码中,从该行的列表中减去一个整数:
for i in range((content2)-1):
但是没有定义从列表中减去整数。len(content2)返回一个整数,该整数等于您想要的列表中元素的数量。
添加回答
举报