【发布时间】:2016-12-09 07:12:09
【问题描述】:
是否有与 R 的grepl 函数等效的简单/单行 python?
strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
【问题讨论】:
标签: python r python-2.7
是否有与 R 的grepl 函数等效的简单/单行 python?
strings = c("aString", "yetAnotherString", "evenAnotherOne")
grepl(pattern = "String", x = strings) #[1] TRUE TRUE FALSE
【问题讨论】:
标签: python r python-2.7
您可以使用列表推导:
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]
【讨论】:
"String$",对吧? (即它只是子字符串匹配)
使用re:
import re
strings = ['aString', 'yetAnotherString', 'evenAnotherOne']
[re.search('String', x) for x in strings]
这不会为您提供布尔值,而是提供同样好的真实结果。
【讨论】:
如果您不需要正则表达式,而只是测试字符串中是否存在子字符串:
["String" in x for x in strings]
【讨论】: