1

I have long four list , I want to check if a word in list_1 and if that word in list_2 with another string (but that substring is still exist) same for all four list , if that substring exist in all four list then print.

So suppose i have these four list :

a=["1","2","45","32","76"]
b=["5","8","345","32789","43"]
c=["362145","9932643","653"]
d=["194532","5423256","76"]

so i wanted to match 45,32 in list a and in list b also because 345 contain 34 but it also contain 45 345 and 32789 contain 32 and list c contain 3621[45] and 99[32]643 contain 32 and so in list d 19[45]32 contain 45 and 542[32]56 contain 32 so if a substring (example 45) is in all 4 list then print.

I tried with "in" method but that doesn't work and then i tried with set() which also doesn't work , How can i do it ?

P.S : is there any method without looping all over list ? because this module is submodule of a large program and that program already contain many loops , if possible without loop otherwise all suggestion welcome :)

3 Answers3

0

Google helped me out.

Use any("45" in s for s in a) this to check if the number is in list a, and so on. It returns True if it finds it.

Edit: Here's an example.

check = input("What number are you looking for?")

if any(check in s for s in a):
    if any(check in s for s in b):
        if any(check in s for s in c):
            if any(check in s for s in d):
                print("something")
El-Chief
  • 383
  • 3
  • 15
0

You can use in with any() and all() functions:

>>> a = ["1", "2", "45", "32", "76"]
>>> b = ["5", "8", "345", "32789", "43"]
>>> c = ["362145", "9932643", "653"]
>>> d = ["194532", "5423256", "76"]
>>> x, y = "45", "32"
>>> all(any(x in i for i in lst) and any(y in i for i in lst) for lst in [a, b, c, d])
True
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
0

Like you described it, its impossible to avoid loops but you can use comprehension lists.

For instance:

a = ["1","2","45","32","76"]
b = ["5","8","345","32789","43"]
c = ["362145","9932643","653"]
d = ["194532","5423256","76"]

result = []
for x in a:
    if (any(x in s for s in b) and
        any(x in s for s in c) and
        any(x in s for s in d)):
        result.append(x)

Every any use an iterable to check if the item x exist in any string of the list b, c or d.

This construction could be rewritten using list comprehension:

result = [x for x in a
          if (any(x in s for s in b) and
              any(x in s for s in c) and
              any(x in s for s in d))]
print(result)

You get:

['2', '45', '32']
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103