遍历 python 中的可迭代数据结构,其值在每次迭代中都会发生变化

Looping through an iterable data structure in python whose value changes every iteration

我的代码如下所示:

input_list = [0,3,5,7,15]
def sample_fun(input_list):
    for idx,ele in enumerate(input_list):
        input_list = [x-2 for x in input_list if (x-2)>0]
        print('Index:',idx,'element:',ele,'New list:',input_list)
sample_fun(input_list)

我想展示的是,在 enumerate 中使用的 input_list 的值在 for 循环中不断变化。我希望 for 循环遍历 input_list 的新值。但似乎 for 循环遍历 input_list 的初始值,即使我正在更改它的值。

Index: 0 element: 0 New list: [1, 3, 5, 13]
Index: 1 element: 3 New list: [1, 3, 11]
Index: 2 element: 5 New list: [1, 9]
Index: 3 element: 7 New list: [7]
Index: 4 element: 15 New list: [5]

我知道 for 循环正在遍历初始枚举输出。 有什么方法可以使 for 循环遍历 input_list 的新值,例如:

  1. 在第一次迭代时index: 0 and element:0, input_list = [1, 3, 8, 13]
  2. 在下一次迭代中,我希望值是这样的 - index: 0 and element: 1 and input_list = [1, 3, 11]
  3. 在下一次迭代中,我希望值是这样的 - index: 0 and element: 1,现在由于元素与前一个元素值相同,我想循环到 - index:1 and element : 3 and input_list = [1, 9] 我希望循环以这种方式运行。

我想遍历 input_list 的变化值。 我不知道该怎么做。如果有人能在这里帮助我,那就太好了。提前致谢!

for 循环中,您不断向 input_list 分配一个新的列表对象:

input_list = [x-2 for x in input_list if (x-2)>0]

for 循环的迭代器基于原始列表对象,因此不会反映分配给 input_list.

的新列表对象

您可以通过切片整个范围来就地更改 input_list

input_list[:] = [x-2 for x in input_list if (x-2)>0]

以便迭代器可以反映对同一列表对象所做的更改。