简体   繁体   中英

List comprehension instead of nested for loop and ifs

I want to write a list comprehension equivalent to the nested for loop and conditions

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))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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