Home > Blockchain >  Using list comprehension as condition for if else statement
Using list comprehension as condition for if else statement

Time:11-28

I have the following code which works well

list = ["age", "test=53345", "anotherentry", "abc"]

val = [s for s in list if "test" in s]
if val != " ":
    print(val)

But what I'm trying to do is using the list comprehension as condition for an if else statement as I need to proof more than one word for occurence. Knowing it will not work, I'm searching for something like this:

PSEUDOCODE
if (is True = [s for s in list if "test" in s])
print(s)
elif (is True = [l for l in list if "anotherentry" in l])
print(l)
else:
print("None of the searched words found")

CodePudding user response:

First of all, avoid using reserved words like "list", to name variables. (Reserved words are always branded as blue).

If you need something like this:

mylist = ["age", "test=53345", "anotherentry", "abc"]
keywords = ["test", "anotherentry", "zzzz"]
    
    for el in mylist:
        for word in words:
            if (word in el):
                print(el)

Use this:

[el for word in keywords for el in mylist if (word in el)]

CodePudding user response:

any in python allows you to see if an element in a list satisfies a condition. If so it returns True else False.

if any("test" in s for s in list): # Returns True if "test" in a string inside list
    print([s for s in list if "test" in s])

CodePudding user response:

First, please don't use "list" as a variable. There is a built-in function called list()...

Could work like this:

list_ = ["age", "test=53345", "anotherentry", "abc"]
val = [s for s in list_ if "test" in s]                #filters your initial "list_" according to the condition set

if val:
    print(val)                                         #prints every entry with "test" in it
else:
    print("None of the searched words found")

CodePudding user response:

Since a non-empty list tests as True (e.g. if [1]: print('yes') will print 'yes') you can just see if your comprehension is empty or not:

>>> alist = ["age", "test=53345", "anotherentry", "abc"]
>>> find = 'test anotherentry'.split()
>>> for i in find:
...   if [s for s in alist if i in s]:i
...
'test'
'anotherentry'

But since it is sufficient to find a single occurance, it would be better to use any like this:

>>> for i in find:
...   if any(i in s for s in alist):i
...
'test'
'anotherentry'
  • Related