繁体   English   中英

使用python中的函数更新列表中的所有项目

[英]update all items in a list using function in python

你能告诉我我在做什么错以及如何解决它。

谢谢

我有一个功能。

def out(some_list):
    test_list = [1,2,3,4]
    result = []

    for i in some_list:
        if i == 1:
            test_list = [0,0,0,0]
        else:
            test_list = test_list

        result.append(test_list)

    return result

如果我们将其打印出来,它将返回:

[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

我要回去

[[0, 0, 0, 0], [1,2,3,4], [1,2,3,4], [1,2,3,4]]

这是因为你在传递这个函数列表中有1作为第一要素的价值。 例如:

out([1,2,3,4]) # ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

逐步检查您的代码:

test_list = [1,2,3,4]
result = []

for i in some_list:           # The value of each element in some_list
    if i == 1:                # If the value is "1" set test_list: [0,0,0,0]
        test_list = [0,0,0,0]
    else:
        test_list = test_list # Otherwise set test_list to itself (doing nothing)

    result.append(test_list)

for i in some_list: 

i的for循环值是您在some_list中所使用的元素的值,而不是我们在列表中所处的元素的索引或位置( 因为此问题似乎是我们some_list

    if i == 1:
        test_list = [0,0,0,0]

如果值为1 ,则test_list将设置为[0,0,0,0] 一旦命中,则仅将[0,0,0,0]值附加到result 因此,如果第一个元素为1那么您将仅在结果中看到值[0,0,0,0] ,否则您将看到[1,2,3,4]直到循环到达列表中的值some_list1

这里有些例子:

out([0,1,2,3]) # [[1, 2, 3, 4], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
out([1,2,3,4]) # [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
out([2,2,5,1]) # [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [0, 0, 0, 0]]

希望这可以更清楚地说明您为何获得该结果。


编辑

关于更新的问题,这里发生的是,当您调用.append(fig)它只是对内存中fig的引用的副本。 基本上,每当更改时,您附加的所有副本也会更改。 您可以通过两种方式处理此问题,首先是在循环范围内定义变量fig ,这样,它是每个循环上的新变量:

 for i in test_list:
   fig = [2, 1]  # <== In the scope of the loop, so each fig is it's on variable
   ...

第二种方法是您可以追加fig[:] ,这意味着它将复制数组fig作为新数组并将其传递给append

for i in test_list:

  if i == '0':
      fig[0] = off
      fig[1] = off
  elif i == '1':
      fig[0] = off
      fig[1] = on

  new_list.append(fig[:]) # <== Copy the array fig and append that value

这是因为您设置了test_list = [0,0,0,0]所以即使在test_list = test_listtest_list = test_list会将结果设置为[0,0,0,0]

尝试使用

def out(some_list):
test_list = [1,2,3,4]
result = []

for i in some_list:
    if i == 1:
        result.append([0,0,0,0])
    else:
        result.append(test_list)

return result

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM