在该循环中迭代的变更列表

时间:2019-02-08 13:30:42

标签: python loops

在我的情况下,我有一个for循环,遍历一个列表,但是我想在所述循环中更改该列表。 之后,我希望for循环遍历新列表。

li = [4,5,6,7,8,9]
for item in li:
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        li = [9,9,9,9,9,9] 

我该怎么做?

3 个答案:

答案 0 :(得分:0)

尽管@BoarGules的评论是正确的,但您可以使用枚举解决问题。

private async void button1_Click(object sender, EventArgs e) 
{
    DataTable table = null;
    //Load data
    this.Text = "Loading ...";
    await Task.Run(async () => {
        await Task.Delay(2000); //Simulating a delay for loading data
        table = new DataTable();
        table.Columns.Add("C1");
        for (int i = 0; i < 10000; i++)
            table.Rows.Add(i.ToString());
    });
    this.Text = "Load data successfully.";

    //Show the other form
    var f = new Form();
    var tree = new TreeView();
    tree.Dock = DockStyle.Fill;
    f.Controls.Add(tree);
    f.Show();

    //Load Tree
    f.Text = "Loading tree...";
    await Task.Run(async () => {           
        await Task.Delay(2000); //Simulating a delay for processing
        Invoke(new Action(() => { tree.BeginUpdate(); }));
        foreach (DataRow row in table.Rows) {
            //DO NOT processing using invoke, just call UI code in INvoke.
            Invoke(new Action(() => { tree.Nodes.Add(row[0].ToString()); }));
        }
        Invoke(new Action(() => { tree.EndUpdate(); }));
    });
    f.Text = "Load tree successfully.";
}

这将输出:

li = [4,5,6,7,8,9]
for i, item in enumerate(li):
    print(li[i])
    if li[i] == 5:
        li = [9,9,9,9,9,9]

答案 1 :(得分:0)

您不应该通过迭代来更改列表。我会使用索引:

for i in range(len(li)):
    if li[i] == 5:
        li = len(li) * [9]

答案 2 :(得分:0)

要了解为什么这行不通,for循环等效于while循环,如下所示:

# for x in y:
#    ...
itr = iter(y)
while True:
    try:
        x = next(itr)
    except StopIteration:
        break
    ...

如果您为y分配了新内容,则该循环不会受到影响,因为它仅在分配给y的原始值上使用迭代器,而没有使用名称y本身。

但是,如果您执行对循环主体中的列表进行变异,则迭代器可能会返回您不期望的值。如果需要更改可迭代对象,最好自己获取迭代器。

li = [4,5,6,7,8,9]
itr = iter(li)
while True:
    try:
        item = next(itr)
    except StopIteration:
        break
    #do something

    if item == 5:
        #now continue iterating through this loop and not the old one
        itr = iter([9,9,9,9,9])