【发布时间】:2021-07-14 07:27:43
【问题描述】:
我的代码如下所示:
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 的新值,例如:
- 在第一次迭代时
index: 0 and element:0, input_list = [1, 3, 8, 13] - 在下一次迭代中,我希望值是这样的 -
index: 0 and element: 1 and input_list = [1, 3, 11] - 在下一次迭代中,我希望值是这样的 -
index: 0 and element: 1,现在由于元素与之前的元素值相同,我想循环到 -index:1 and element : 3 and input_list = [1, 9]我希望循环以这种方式运行。
我想遍历 input_list 的变化值。 我不知道该怎么做。如果有人可以在这里帮助我,那就太好了。提前致谢!
【问题讨论】:
标签: python-3.x loops for-loop enumerate