如何在python中使用.endswith函数测试几个条件

And*_* C. 2 python string kwargs

我有一个包含不同扩展名的文件列表.淘汰者我想筛选出只有那些扩展.bam,.bai,.vcf和更多一些.有没有办法使用带有多个参数的endswith函数而不是多次重复它?

所以代替:

for name in list:
    if name.endswith('.bam') or name.endswith('.bai') or name.endswith('.bai'):
        # do stuff
Run Code Online (Sandbox Code Playgroud)

就像是:

for name in list:
    if name.endswith(*['.bai', '.bam', '.vcf']):
        # do stuff
Run Code Online (Sandbox Code Playgroud)

Pet*_*per 9

endswith从Python 2.5开始接受可能后缀的元组.所以它只是:

if name.endswith(('.bai','.bam','.vcf')):
Run Code Online (Sandbox Code Playgroud)

https://docs.python.org/3/library/stdtypes.html#str.endswith