[英]simplest python equivalent to R's grepl
是否有一个简单/单行python等同于R的grepl
函数?
strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
您可以使用列表理解:
strings = ["aString", "yetAnotherString", "evenAnotherOne"]
["String" in i for i in strings]
#Out[76]: [True, True, False]
或者使用re
模块:
import re
[bool(re.search("String", i)) for i in strings]
#Out[77]: [True, True, False]
或者使用Pandas
(R用户可能对此库感兴趣,使用数据框“类似”结构):
import pandas as pd
pd.Series(strings).str.contains('String').tolist()
#Out[78]: [True, True, False]
使用re
可以使用单行等效:
import re
strings = ['aString', 'yetAnotherString', 'evenAnotherOne']
[re.search('String', x) for x in strings]
这不会给你布尔值,但是同样的结果也同样好。
如果您不需要正则表达式,而只是测试字符串中是否存在susbtring:
["String" in x for x in strings]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.