RHK*_*-S8 0 python list python-2.7
嘿我正在尝试更改我的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,]
for i in range((content2)-1):
if content2[i] == 0.0:
content2[i] = None
print content2
Run Code Online (Sandbox Code Playgroud)
它需要产生:
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,]
Run Code Online (Sandbox Code Playgroud)
我也尝试了其他各种方法.有人有个主意吗?
您应该避免在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]
Run Code Online (Sandbox Code Playgroud)
要改变content2此列表理解的结果,请执行以下操作:
content2[:] = [float(x) if x else None for x in content2]
Run Code Online (Sandbox Code Playgroud)
您的代码不起作用,因为:
range((content2)-1)
Run Code Online (Sandbox Code Playgroud)
你试图减去1一个list.另外,range终点是独家(它上升到终点- 1,你所减去1再次)你是那么是什么range(len(content2))
您对代码的这种修改有效:
for i in range(len(content2)):
if content2[i] == 0.0:
content2[i] = None
Run Code Online (Sandbox Code Playgroud)
使用intPython 中的s等于0评估为false 的隐含事实更好,所以这同样也可以正常工作:
for i in range(len(content2)):
if not content2[i]:
content2[i] = None
Run Code Online (Sandbox Code Playgroud)
您可以习惯于为列表和元组执行此操作,而不是if len(x) == 0按照PEP-8的建议进行检查
我建议的列表理解:
content2[:] = [float(x) if x else None for x in content2]
Run Code Online (Sandbox Code Playgroud)
在语义上等同于
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
Run Code Online (Sandbox Code Playgroud)