0

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

我也尝试过其他各种方法。有人有想法吗?

4

3 回答 3

6

您应该避免在 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从 a中减去listrange端点也是独占的它上升到端点- 1,你又要从中减去1)所以你的意思是range(len(content2))

您的代码的这种修改有效:

for i in range(len(content2)):
    if content2[i] == 0.0:
        content2[i] = None

int使用Python 中的 s 等于评估为 false的隐含事实会更好,0因此这也同样适用:

for i in range(len(content2)):
    if not content2[i]:
        content2[i] = None

您也可以习惯于对列表和元组执行此操作,而不是按照PEP-8if len(x) == 0的建议进行检查

我建议的列表理解:

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
于 2013-06-10T14:15:00.387 回答
3

您应该在这里使用列表理解:

>>> 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]
于 2013-06-10T14:15:58.247 回答
1

稍微修改你的代码会得到想要的结果:

for i in range(len(content2)):
    if content2[i]==0:
        content2[i] = None

在您的代码中,您从行中的列表中减去一个整数:

for i in range((content2)-1):

但未定义从列表中减去整数。len(content2) 返回一个整数,该整数等于列表中的元素数,这正是您想要的。

于 2013-06-10T14:18:19.700 回答