简体   繁体   English

列表理解而不是嵌套for循环和ifs

[英]List comprehension instead of nested for loop and ifs

I want to write a list comprehension equivalent to the nested for loop and conditions 我想写一个等效于嵌套的for循环和条件的列表理解

I tried writing 我尝试写作

lst.append(i,j for i in range(2,num) for j in range(2,i) if num%i==0 if i%j!=0)

Which gives me the error: 这给了我错误:

Generator expression must be parenthesized 生成器表达式必须带括号

I also tried 我也试过

lst=[(i,j) for i in range(2,num) for j in range(2,i) if num%i==0 if i%j!=0] 

which doesnt throw error but I am not getting the desired result 这不会引发错误,但是我没有得到预期的结果

num=int(input("Enter a number:"))
lst=[]
for i in range(2,num):
    if num%i!=0:
        continue
    else:
        isprime=False
        for j in range(2,i):
            if i%j==0:
                isprime=True
                break
        if not isprime:
            lst.append(i)
for ele in lst:
    print(ele)

This program will give the prime factors of a number entered 该程序将给出输入数字的主要因素

If you're looking to replicate exactly what you have there, you can try something like this: 如果您想完全复制那里的内容,可以尝试执行以下操作:

lst = [i for i in range(2, num) if num % i == 0 and all(i % j for j in range(2, i))]

Though it's not quite as efficient since it lacks the ability to do break. 尽管它效率不高,因为它缺乏突破的能力。

If you're instead looking to find all of the primes via list comprehension, this isn't a bad way to accomplish that: 如果您想通过列表理解来查找所有素数,那么这并不是一个坏方法:

lst = [x for x in range(2, num) if all(x % y != 0 for y in range(2, int(x ** 0.5) + 1))]

一种简单的(但不是非常有效的)列表理解方法如下:

primefactors = [n for n in range(2,num) if num%n==0 and all(n%f for f in range(2,n))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM