【发布时间】:2020-12-05 07:22:52
【问题描述】:
我正在尝试编写代码来选择列表中的素数。用户给出一个极限,程序显示从 2 到极限的所有素数。我试图尽可能减少行数,但对一些我无法理解的情况感到惊讶。如果您能帮助我,我将不胜感激。
我写了这段代码:
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
lista = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in lista if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
它按我的预期运行,但是当我尝试删除第一个列表分配行并将范围函数直接包含到理解中时,它不起作用。为什么?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in range(2, limit + 1) if i == p or i % p != 0]
#or lista = [i for i in [*range(2, limit + 1)] if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#Ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
其他问题。由于 range 行不是列表,我修复它只是为了改进代码,但是当我将值的名称从“lista”更改为另一个名称时,我发现它也不起作用。为什么?
# returns all integers from 2 to a limit given by the user.
def primes(limit):
# generates the numbers.
nums = range(2, limit + 1)
p = 2
while p < limit:
#filters the prime numbers and places in a list.
lista = [i for i in nums if i == p or i % p != 0]
p += 1
return lista
def main():
#asks the user for the limit number.
l = int(input("Enter the limit: "))
#call the function which selects the numbers and returns the result.
return print(primes(l))
#ensures that the main program only runs when the functions have not been imported into another file.
if __name__ == '__main__':
main()
感谢您的关注。
【问题讨论】:
-
因为你在
while p < limit循环中修改了lista,所以每次运行循环的启动顺序都不一样。当您将lista更改为range(2, limit + 1)或nums时,您将开始序列更改为一个常量值,您的代码将只过滤掉最后一个p值的倍数。
标签: python list range list-comprehension