如何在for loop-python中编辑列表元素

如何在for loop-python中编辑列表元素,python,list,Python,List,我有一个数字列表,我正试图循环浏览这个列表,并根据特定的标准更改每个数字。但是我的代码并没有改变列表,当我在最后再次打印它时仍然是一样的。我的代码如下: list = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]] for x in list: if (x >= 0): x = 100 if (x < 0): x = -100 print list li

我有一个数字列表,我正试图循环浏览这个列表,并根据特定的标准更改每个数字。但是我的代码并没有改变列表,当我在最后再次打印它时仍然是一样的。我的代码如下:

list = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]]

for x in list:
    if (x >= 0):
        x = 100
    if (x < 0):
        x = -100
print list
list=[[10.0,4.0,10.0,10.0,4.0,0.0,10.0,10.0,10.0,4.0,6.0]]
对于列表中的x:
如果(x>=0):
x=100
如果(x<0):
x=-100
打印列表

看了这个,问题没有解决你有两个问题:一,你的列表实际上是一个列表列表;第二,您没有正确地为列表赋值。试着这样做:

# Loop over the indices of the list within the list
for i in range(len(list[0])):
    if (list[0][i] >= 0):
        list[0][i] = 100
    else:
        list[0][i] = -100
print list
有一些方法可以使这更有效和更具普遍性,但是如果保持
for
循环样式,上述代码将适用于您的情况

例如,您也可以这样做(本质上与列表迭代形式相同,并在列表列表中的每个列表中循环,以防您有多个列表):

对于多个列表的列表,其工作原理如下:

old = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0],[-2, 2, -2]]

new = [[100 if lst[i] >=0 else -100 for i in range(len(lst))] for lst in old]

>>> new
[[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], [-100, 100, -100]]
另外,通常将列表称为
list
,因为
list
已经是python中的内置类型

用于一维列表

list = [100 if x >= 0 else -100 for x in list]
在你的问题中,你有一个列表。指列表中的列表。 在上面的示例中,您可以看到我迭代了每个元素,并根据元素设置了值

如果你有2D列表

list = [[100 if x >= 0 else -100 for x in items] for items in list]

使用您发布的代码

list = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]]

for i in range(len(list[0])):
    if list[0][i] >= 0:
        list[0][i] = 100
    else:
        list[0][i] = -100
print(list)

第一个问题 您得到了一个值列表
[[]]
,而不是简单的列表
[]

第二个问题您没有改变列表,您需要直接按索引更改项

对于使用索引的迭代,可以使用

第三条注释在您的情况下,如果,最好使用
else
而不是两条

list = [10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]

for i, x in enumerate(list):
    if (x >= 0):
        list[i] = 100
    else:
        list[i] = -100
print list
p.S.也许你不应该改变最初的列表?也许最好还是返回新的列表

list = [10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]

def return_new_list(list):
    new_list = []
    for x in list:
        if (x >= 0):
            new_list.append(100)
        else:
            new_list.append(-100)
    return new_list

print return_new_list(list)

阅读:你有一个浮动列表,你将其视为一个浮动列表。除了您没有更改列表项,而是更改
x
。是的,它是列表中的列表。然后将循环中的int列表与int进行比较。这就是为什么它是错误的。@arundeepak不仅仅如此。这就是它引发错误的原因。但即使这是正确的,这段代码也不会改变列表。@Ev.Kounis,yep:)什么是
项目
?错误地键入而不是列表
list = [10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]

def return_new_list(list):
    new_list = []
    for x in list:
        if (x >= 0):
            new_list.append(100)
        else:
            new_list.append(-100)
    return new_list

print return_new_list(list)