My For loop won#39;t iterate through a list(我的 For 循环不会遍历列表)
问题描述
我必须确定列表中的所有数字是否都是素数,然后根据结果返回布尔真"或假"语句.我在 for 循环中做了一些条件语句来查看数字是否为素数.
I have to determine if all the numbers in a list are prime numbers and then return a boolean "True" or "False" statement depending on the outcome. I made some conditional statements inside of a for loop to see if the number was prime or not.
代码如下:
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
break
elif (i % 2 == 0) and (i % i == 1):
is_prime = False
return is_prime
break
else:
is_prime = True
return is_prime
问题是,我在 Python Visualizer 中看到了这一点,for 循环在检查列表中的第一个值后停止迭代.我不明白为什么语法与我过去使用的 for 循环相同.
The problem is, and I saw this in the Python Visualizer, the for loop stops iterating after checking the first value in the list. I don't understand why as the syntax is the same as for loops I've used in the past.
我插入了一些示例值,例如:all_primes([5,2,11,37]) 或 all_primes([5,2,4,37])并且返回值始终为真,因为 5 是列表中的第一个数字,也是唯一被迭代的数字.
I plugged in some example values like: all_primes([5,2,11,37]) or all_primes([5,2,4,37]) and the return value is always true since 5 is the first number on the list and the only number that is being iterated.
关于为什么的任何想法?
Any ideas as to why?
推荐答案
你的 if/else 中有一个 return 和一个 break块,你应该摆脱它们.else 中的 return 也应该在外面,否则只要他找到素数",它就会返回.
You have a return and a break in your if/else block, you should get rid of them. Also the return in the else should be outside, or it will just return whenever he finds a "prime".
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
elif (i % 2 == 0):
is_prime = False
return is_prime
else:
is_prime = True
return is_prime
在此之后,您应该知道,您并没有真正检查素数.这不是最有效的方法,但它很清楚如何:
After this, you should know, that you are not really checking primes. Here is not the most efficient way but its clear how to:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
return all(map(checkPrime, xs))
如果没有 map 函数,您只需要使用 for 循环进行迭代:
without the map functions, you just have to iterate with a for loop:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
for n in xs:
if not checkPrime(n):
return False
return True
这篇关于我的 For 循环不会遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我的 For 循环不会遍历列表
基础教程推荐
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
