Boolean operations (Python 3.4) - is there a way to simplify long conditional statements?

I have the following list of integers that I need to compare with eachother:

compare = [[2,4,5,7,8,10,12],[1,3,5,8,9,10,12],[1,2,4,6,8,10,11,12],[2,3,4,6,7,9,12]]

Even if you did not list the lists of names in lists in Python (I think), we simply call each count a, b, c and d.

What I want to do is make a for loop, which can compare if any one integer is present in 2, 3, or in all lists. The cycle itself is simple, it iterates over all integers in ad, but the conditions under which the comparisons are made are rather complicated or perhaps just long, for example, for example:

    if i in a and i in b, or i in a and i in c... or i in a and i in b and i in c... or i in (every list):
        pattern.append (i)

Obviously, this is impractical. I was looking for a solution to the problem, but to no avail. In addition, there would be | can operators be used anyway, or should I stick with AND and OR?

Thanks in advance for your help!

+4
4

, c , (a, b, d)? any() :

compare = [
    [2, 4, 5, 7, 8, 10, 12],
    [1, 3, 5, 8, 9, 10, 12],
    [1, 2, 4, 6, 8, 10, 11, 12],
    [2, 3, 4, 6, 7, 9, 12]
]

a, b, c, d = compare

pattern = []
for value in c:
    if any(value in lst for lst in (a, b, d)):
        pattern.append(value)

a, b, c, d = compare , 4 compare any() .

+2

itertools.chain, , , :

>>> import itertools
>>> new_list=list(itertools.chain(*compare))
[2, 4, 5, 7, 8, 10, 12, 1, 3, 5, 8, 9, 10, 12, 1, 2, 4, 6, 8, 10, 11, 12, 2, 3, 4, 6, 7, 9, 12]

>>> pattern=[i for i in new_list if new_list.count(i)>2]
>>> pattern
[2, 4, 8, 10, 12, 8, 10, 12, 2, 4, 8, 10, 12, 2, 4, 12]
+2

Set() , .

a = [2,4,5,7,8,10,12]
b = [1,3,5,8,9,10,12]
set(a).intersection(set(b)) 

=> set([8, 10, 12, 5])

+1

, :

present = [any_given_integer in L for L in compare]

Now there are values ​​such as [True, True, False, False]etc.

Then you can perform tests such as:

if present.count(True) == 2:
    ...

or

if all(present):
    ...

and etc.

+1
source

All Articles