简体   繁体   中英

nested loops and conditional checks in list comprehensions (python)

I'm currenty learning list comprehension in Python and I want to write a function that takes two lists, a and b , and returns all elements of a that are divisible by all elements of b .

The equivalent of this (not using list comprehension) would be:

    a = [10, 5]
    b = [5, 2]
    c = []
    d = True
    for i in a:
        for j in b:
            if i % j != 0:
                d = False
        if d:
            c.append(i)
    return c

How can I do this with list comprehension? I currently have [x for x in a for y in b if x % y == 0] but that only requires x to match one of the items in b, not all of them.

Try this one:

a = [10, 5]
b = [5, 2]

res = [x for x in a if all(x % y == 0 for y in b)]

for completion on @superb rain 's comment. Here is also an example for any(...):

res = [x for x in a if not any(x % y != 0 for y in b)]

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