Home > OS >  How to get items that are true for ANY() method in Python
How to get items that are true for ANY() method in Python

Time:06-07

Say:

x = 'A/B'
any(signs in x for signs in ['/' , ' ', '-'])

How to get the signs it found true in the iteration? Here's a way

for sign in ['/' , ' ', '-']:
    if sign in x:
        print(sign)

Is there a better one liner way of doing it? (Without the for loop maybe)

CodePudding user response:

My solution

from re import findall
findall(r'[/ -]', x)

But please note there are some subtle differences in the various suggestions:

  • any will stop (and of course return True, not what it found) as soon as it finds one sign. So if your input string is very long and has a sign in the first few position it will be quicker than anything else.
  • your loop will return once each sign which appears in the input string, and not necessarily in the order they appear
  • The list comprehension, filter(), and findall() will return all the signs in the input string, as many times as they appear and in the order they are found

CodePudding user response:

With the few modifications to the any expression, you can get whether each of the signs is in the expression, which signs are in the expression, or just the first such sign:

>>> any(sign in x for sign in ['/' , ' ', '-'])
True
>>> [sign in x for sign in ['/' , ' ', '-']]
[True, False, False]
>>> [sign for sign in ['/' , ' ', '-'] if sign in x]
['/']
>>> next((sign for sign in ['/' , ' ', '-'] if sign in x), None)
'/'

(In the last one, None is the default in case no such element exists.)

CodePudding user response:

I would use a custom function, if the logic is complex, or filter with a lambda function if the logic is simple, like in your case.

def func(string, signs):
    for c in string:
        if c in signs:
            yield c

selected = list(func("A/B", ["/", " ", "-"]))
print(selected) #['/']


selected = list(filter(lambda i: i in ["/", " ", "-"], "A/B"))
print(selected) #['/']
  • Related