[英]Pythonic way to find any item from a list within a string
The problem is simple enough. 问题很简单。 I'm writing a function which returns true if the string contains any of the illegal names.
我正在编写一个函数,如果该字符串包含任何非法名称,则返回true。
line is a string. line是一个字符串。
illegal_names is an iterable. illegal_names是一个可迭代的。
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?
任何人都可以建议一个更整洁,更pythonic的方式来写这个? Could I use a list comprehension or regex?
我可以使用列表解析还是正则表达式?
any(name in line for name in illegal_names)
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: 并且您现在想要确定您的
line
是否包含非法名称之一,然后使用广泛的列表理解和长度检查来执行此操作:
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. 非常简单,简短,与其他
lambda
版本相比易于阅读和取消。
-Colin- -Colin-
I go with @larsmans solution, but there another ways of doing it. 我选择了@larsmans解决方案,但还有另外一种方法。
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
这也可以使用
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 lamdba版本可读性太强
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.