删除特定值上下的列表元素

0 投票
1 回答
47 浏览
提问于 2025-04-13 01:59

我有下面的代码,其中有一个列表里面包含两个子列表。我想要删除每个子列表中高于或低于某些特定值的元素。但是我尝试的方法没有成功,因为它只删除了一些值,我不明白为什么会这样。

liste = [[1,2,3,4], [3,4,5,6,7,8,9]]

for a in liste:
    print(a)
    for b in liste[liste.index(a)]:
        print(b)
        if b < 3:
            print(f"{b} < 3")
            liste[liste.index(a)].remove(b)

    for c in liste[liste.index(a)]:
        print(c)
        if c > 6:
            print(f"{c} > 6")
            liste[liste.index(a)].remove(c)

print(liste)

1 个回答

1

在遍历一个列表的时候,不应该直接修改它,因为这样会导致无法找到所有的元素。更好的方法是使用列表推导式来创建新的列表。

所以在你上面的例子中,你只需要复制那些符合条件的元素,方法如下:

listd = []  # create a new list
listx = [n for n in liste[0] if n > 2] # capture all items greater than 2
listd.append(listx) # add this to listd
listy = [n for n in liste[1] if n < 7] # capture all items less than 7
listd.append(listy) # add this to listd
print(listd) # display the new list

撰写回答