简体   繁体   中英

Python for loop inside for loop/

I am trying to find two numbers in a list which are divisible by each other. I have managed to do this by placing two for loops that loop over the same list to compare numbers until a pair is found.

My Question:

Is it possible to easily compress this code to one or two lines using a conditional statement?

def FindDivisible(j):
    for i in j:
        for m in j:
            if int(i) % int(m) == 0 and int(i) != int(m):
                return([int(i),int(m)])

I do understand that this would not be very pythonic at all. I do however want to know if it is possible and what would be a good way for going about this.

This one-liner will get all divisible combinations of the elements in iterable j :

[([int(i),int(m)]) for m in j for i in j if int(i) % int(m) == 0 and int(i) != int(m)]

The above is just your code translated into a list comprehension . One difference is that this will find all combinations while your original looping code will return just the first successful combination. If you want to exit after the first combination, then the explicit looping is the right choice.

For example:

>>> j=range(2,5)
>>> [([int(i),int(m)]) for m in j for i in j if int(i) % int(m) == 0 and int(i) != int(m)]
[[4, 2]]

You can probably use itertools.product

http://docs.python.org/library/itertools.html#itertools.product

Example as

for var1, var2 in itertools.product(xrange(min1, max1, step1), xrange(min2, max2, step2)):
    # stuff

let use itertool combinaison and filter

in 2 lines :

from itertools import combinations
alist =[(x,y) if  (x%y==0 or y%x==0 and x!=y ) else None for x,y in combinations(l, 2)]
L = list(filter(None, alist))

Use itertools.product . Note that it is simpler to map int over the original input list once, rather than constantly converting individual elements.

from itertools import product
def find_divisible(j):
    return [(i, m) for (i, m) in product(map(int, j), repeat=2) 
             if i % m == 0 and i != m]

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