Reputation: 1758
The problem is simple enough. I'm writing a function which returns true if the string contains any of the illegal names.
line is a string.
illegal_names is an iterable.
def has_illegal_item(line, illegal_names):
illegal_items_found = False
for item in illegal_names:
if item in line:
illegal_items_found = True
break
return illegal_items_found
So this works fine, but it seems a bit clumsy and long-winded. Can anyone suggest a neater and more pythonic way to write this? Could I use a list comprehension or regex?
Upvotes: 3
Views: 320
Reputation: 20419
I go with @larsmans solution, but there another ways of doing it.
def check_names(line, names):
#names should be set
parsed_line = set(line.replace(',', '').split())
return bool(parsed_line.intersection(names))
This can also be written using lambda
In [57]: x = lambda line, names: bool(set(line.replace(",", "").split()).intersection(names))
In [58]: x("python runs in linux", set(["python"]))
Out[58]: True
lamdba version can be overkill of readability
Upvotes: 0
Reputation: 1427
let's have a look on following sample:
line = "This is my sample line with an illegal item: FOO"
illegal_names = ['FOO', 'BAR']
and you want now to find out whether your line
contains one of the illegal names, then you do this with the widespread List Comprehension and a length check:
is_correct = not bool(len([ hit for hit in illegal_names if hit in line ]))
# or
is_correct = len([ hit for hit in illegal_names if hit in line ]) == 0
Pretty easy, short and in relation to other lambda
version easy to read and unterstand.
-Colin-
Upvotes: 1