如何在迭代时从列表中删除元素

问题描述 投票:0回答:1

嘿,我有一个问题,我想从列表中删除一些元素,问题是它更改了索引,并且他们不知道如何删除实际需要的索引

所以它删除了“盐”,但没有删除“糖”,我认为是因为索引在下一次迭代中从0-9传递到0-8

它给出的结果:[“苹果”,“橙子”,“胡椒”,“橙子”,“蛋糕”,“树”,“树”,“叶”,“糖”]

我想要的结果:[“苹果”,“橙子”,“胡椒”,“橙子”,“蛋糕”,“树”,“树”,“叶子”]

#list to match
fi_names = ["apple", "orange", "pepper", "orange", "cake", "tree", "tree", "leaf"]

#list to modify to match the first one
se_names = ["apple", "orange", "pepper", "orange", "cake", "tree", "tree", "leaf", "salt", "sugar"]


#susbtract list to get x_names = ["salt", "sugar"]
x_names = list( set(se_names) - set(fi_names) )


#iterate in the second list to try to remove the extra elements by index
for i, e in enumerate(se_names):

    if e in x_names:
        se_names.pop(i)



print(se_names)
python list loops iteration
1个回答
0
投票

不要在迭代列表时修改列表。

Do 创建一个包含您想要的项目的新列表。

se_names = [x for x in se_name if not (x in x_names)]
© www.soinside.com 2019 - 2024. All rights reserved.