Python: how to find the element in a list which match part of the name of the element

六月ゝ 毕业季﹏ 提交于 2020-07-22 21:33:07

问题


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.


回答1:


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



回答2:


Try this -

for w in word:
     for file in file_list:
         if w in file:
             print file



回答3:


You can try this using list comprehension:

word = ['U12','U13','U14']
file_list =['h_ABC_U12.csv','h_GGG_U13.csv','h_HVD_U14.csv','h_MMMB_U15.csv']

print [i for i in file_list for b in word if b in i]



回答4:


Surely

for x in range(len(word)):
    for file in file_list:
        if x in file:
            print file

Would do the job?




回答5:


This should perform better:

for file_name in file_list:
    the_word = next((w for w in word if w in file_name), None)
    if the_word:
        print the_word
        print file_name

Or to get the list of all file names:

[file_name for file_name in file_list if next((w for w in word if w in file_name), None)]



回答6:


word = ['U12','U13','U14']
file_list = ['h_ABC_U12.csv','h_GGG_U13.csv','h_HVD_U14.csv','h_MMMB_U15.csv']

for file_name in file_list:
  for w in word:
    if w in file_name:
      print(w,file_name)

RESULT

U12 h_ABC_U12.csv
U13 h_GGG_U13.csv
U14 h_HVD_U14.csv


来源:https://stackoverflow.com/questions/44137151/python-how-to-find-the-element-in-a-list-which-match-part-of-the-name-of-the-el

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!