我希望能够获得一个数字范围为3或更高的列表,并将其变成仅在1到3范围内的数字列表。该代码只删除一些高于3的数字,并保留其他数字。我想把所有3以上的数字都从列表中删除。
thelist= [1,8,9,2,3]
for element in thelist:
if int(element) >= 4:
thelist.remove(element)
elif int(element) <= 3:
continue
print(thelist)
# prints [1, 9, 2, 3]. Number 8 was removed but not number 9
你不需要其他部分,所以你可以删除它。
但是你的代码不起作用,因为你需要先复制列表,你可以在这里阅读更多
解决方案:在for循环中的列表后添加[:]
thelist = [1,8,9,2,3]
for element in thelist[:]:
if int(element) >= 4:
thelist.remove(element)
print(thelist)
在迭代列表时试图修改列表会导致与预期不同的行为。
在您的示例中,如果删除8
,那么9
现在会插入到8
所在的位置,因此在下一次迭代中会被跳过。
相反,您希望创建一个新列表,其中仅包含符合您的条件的值。这是一个使用列表理解的好机会。
thelist = [x for x in thelist if x < 4]
如果您希望检查每个元素是否为1、2或3:
thelist = [x for x in thelist if x in {1, 2, 3}]