猿问

python更改整数/在列表中浮动为无

嘿,我正在尝试更改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

它需要产生:


   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,]

我也尝试了其他各种方法。有人知道吗?


摇曳的蔷薇
浏览 202回答 3
3回答

慕村225694

您应该避免在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

繁花不似锦

您应该在此处使用列表理解:>>> 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]

牛魔王的故事

稍微修改您的代码即可获得理想的结果:for i in range(len(content2)):    if content2[i]==0:        content2[i] = None在您的代码中,从该行的列表中减去一个整数:for i in range((content2)-1):但是没有定义从列表中减去整数。len(content2)返回一个整数,该整数等于您想要的列表中元素的数量。
随时随地看视频慕课网APP

相关分类

Python
我要回答