Python:如何在列表中查找与元素名称的一部分匹配的元素 [英] Python: how to find the element in a list which match part of the name of the element
本文介绍了Python:如何在列表中查找与元素名称的一部分匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关键字列表,可从文件名列表中查找.例如,如果关键字为'U12'
,我想查找包含'U12'
的csv文件,该文件为'h_ABC_U12.csv'
并打印出来.
I have a list of keyword to find from a list of file name. Example, if the keyword is 'U12'
, I want to find the csv file that contain 'U12'
which is 'h_ABC_U12.csv'
and print it out.
word = ['U12','U13','U14']
file_list = ['h_ABC_U12.csv','h_GGG_U13.csv','h_HVD_U14.csv','h_MMMB_U15.csv']
for x in range (len(word)):
if word[x] in file_list:
#print the file name
这是代码的一部分,但在进行某些搜索后无法继续.我需要与单词匹配的全名才能打印出来.
This is part of the code but unable to continue after some searches. I need the full name that match the word to print out.
推荐答案
我建议使用 os.path.splitext
获取不带扩展名的文件名.
I suggest using os.path.splitext
to get the filename without extension.
>>> from os.path import splitext
>>> for f in file_list:
... name = splitext(f)[0]
... if any(name.endswith(tail) for tail in word):
... print(name)
...
h_ABC_U12
h_GGG_U13
h_HVD_U14
这篇关于Python:如何在列表中查找与元素名称的一部分匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文