python - 列表查找中部分字符串匹配的单行代码

标签 python

是否有更简单的方法来执行以下操作?

filename = 'vudu_hail_20140101.xml'
acceptable_stems = ['vudu', 'google']

process_file = False
for acceptable_stem in acceptable_stems:
    if acceptable_stem in filename:
        process_file = True

基本上,我正在寻找一个 bool 决定因素来判断文件名中是否包含某个词干。这如何用一行代码来完成?

最佳答案

使用 any 怎么样?关键字:

any([acceptable_stem in filename for acceptable_stem in acceptable_stems])

示例:

>> filename = 'vudu_hail_20140101.xml'
>> acceptable_stems = ['vudu', 'google']
>> any([acceptable_stem in filename for acceptable_stem in acceptable_stems])
True

>> filename = 'vudu_hail_20140101.xml'
>> acceptable_stems = ['vuduf', 'google']
>> any([acceptable_stem in filename for acceptable_stem in acceptable_stems])
False

关于python - 列表查找中部分字符串匹配的单行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492839/

相关文章:

python - python opencv检测图像完全白

python - 如何从 python 中执行加载数据命令

python - 如何为 groupby DataFrame 创建滚动百分比

python - 尝试通过使用 h5py 更改索引字段类型来缩小 HDF5 文件的大小

python - Python负指数与除法

python - 计算多组数据的平均值(性能问题)

python - Cython:创建返回数组的 C 函数

python - 如何以编程方式运行主/从 Locust 运行程序,以便从服务器在最后停止

python - 在 Python 中查找第 K 个最大元素的总体复杂性

python - Beautifulsoup、Python 和 HTML 自动页面截断?