问题描述
我正在尝试在 python 中编写代码来过滤前 n 个整数的列表,这些整数在被分割时的余数为 1。但是,它似乎没有根据我拥有的打印语句检查列表中的每个整数。我不知道为什么。我刚刚开始学习代码,所以请耐心等待。我怀疑这是我没有看到的明显内容。
以下是我到目前为止的代码:
def main():
checkUpTo = 20
listofInts = list(range(checkUpTo))
filterList = [3]
boolList = []
for d in filterList:
print("checking list: " + str(listofInts) + " for rem=1 when divided by " + str(d))
for x in listofInts:
print("checking: " + str(x))
isDivisible = checkIfDivisible(x,d)
if isDivisible==False:
listofInts.remove(x)
print("got list: " + str(listofInts))
print(listofInts)
def checkIfDivisible(number,divisor):
remainder = number % divisor
print(str(number) + "%" + str(divisor) + "=" + str(remainder))
if number % divisor == 1:
return True
if number % divisor != 1:
return False
if __name__ == "__main__":
main()
感谢您的帮助
编辑:我的输出:
checking list: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] for rem=1 when divided by 3
checking: 0
0%3=0
checking: 2
2%3=2
checking: 4
4%3=1
checking: 5
5%3=2
checking: 7
7%3=1
checking: 8
8%3=2
checking: 10
10%3=1
checking: 11
11%3=2
checking: 13
13%3=1
checking: 14
14%3=2
checking: 16
16%3=1
checking: 17
17%3=2
checking: 19
19%3=1
got list: [1,19]
[1,19]
不知道为什么不检查 1,3 等
解决方法
listOfInts.remove(x)
更改您在 listOfInts
中迭代的对象 (for
),这将更改循环中的迭代次数。
考虑:
l = [1,2,3,4,5]
for index,value in enumerate(l):
print(l)
l.remove(value)
print(index + 1) # 3,not 5.
不是从 listOfInts
中删除元素,而是遍历 x in range(checkUpTo)
,如果您发现 可以被 d
整除,请将其添加到 set
{1}}。
看看 For 循环,listOfInts.remove(x)
从列表中删除元素。因此,您的列表中没有余数为一的元素。
for x in listOfInts:
print("checking: " + str(x))
isDivisible = checkIfDivisible(x,d)
if isDivisible == False:
listOfInts.remove(x)
让我们了解一下 for 循环中发生了什么
-
列表包含从 0 到 19 的元素。
-
for 循环取 0 并将其传递给
checkIfDivisible
函数。 -
0%3=0 返回
False
。 -
isDivisible == False
,所以listOfInts.remove(x)
从位置 0 移除元素。 -
for 循环现在获取下一个项目,因为我们已经从 0 位置删除了项目,现在在 0 位置我们有元素 1 在 1 位置,我们有元素 2,依此类推。
-
因此打印语句不显示元素 1。
for x in listOfInts: print("checking: " + str(x)) isDivisible = checkIfDivisible(x,d) print(isDivisible) if isDivisible == False: print(x) print(listOfInts) listOfInts.remove(x)
检查:0 0%3=0 错误的 0 [0,1,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] 检查:2 2%3=2 错误的 2 [1,19]