【问题标题】:Looping through an iterable data structure in python whose value changes every iteration循环遍历python中的可迭代数据结构,其值每次迭代都会改变
【发布时间】: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 的新值,例如:

  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 的变化值。 我不知道该怎么做。如果有人可以在这里帮助我,那就太好了。提前致谢!

【问题讨论】:

    标签: python-3.x loops for-loop enumerate


    【解决方案1】:

    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]
    

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

    【讨论】:

    • 当我尝试代码时,随着 input_list 值的变化,索引继续增加。它正在使用 input_list 的新值,但我希望迭代再次从 index:0 开始,正如我在我希望循环如何迭代的解释中所示。我知道使用枚举可能无法做到这一点。但我正在寻找一种方法来做到这一点。如果您的解决方案可以做到这一点,那就太好了!
    • 那是您当时描述的一种非常自定义的行为。您当然必须创建自己的类来实现 Python 的 iterator protocol 以生成您正在寻找的可迭代对象。请自己尝试,如果遇到困难,请发布另一个特定于新代码的问题。
    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 2019-02-25
    • 2019-01-25
    • 1970-01-01
    • 2023-03-25
    • 2020-01-05
    • 2014-01-28
    • 1970-01-01
    相关资源
    最近更新 更多