简体   繁体   中英

Check if each element of one list is a multiple of all the elements of another list

I have two lists; S and T. I want to check if each element of T is a multiple of all the elements of S. Then append that element of T to a new list V if the condition is true for all elements of S.

Input

S = [2, 4]
T = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

Expected Output

V = [4, 8, 12, 16]

I tried this code below but got a wrong output;

V = [i for i in T for j in S if i % j == 0]
print(V)

Current wrong output

V = [4, 4, 6, 8, 8, 10, 12, 12, 14, 16, 16]

Use all() to check if all conditions are True:

S = [2, 4]
T = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

V = [i for i in T if all(i % j == 0 for j in S)]
print(V)

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