python 查找列表中的列表元素的一部分(函数)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 查找列表中的列表元素的一部分(函数)相关的知识,希望对你有一定的参考价值。

# A function for creating a list of file paths in multiple subdirs
# FileKeys_any is a user defined list and is part of the filename that is listed by os.walk, see the examples below
# FileKeys_any = ["18_48", "18_49"]
# name = ["DM 18_48.xlsx", "DM 18_49.xlsx"]

def list_factory_files(dir, FileKeys_any):
    r = []
    for root, dirs, files in os.walk(dir):
        for name in files:
            if any(z in name for z in FileKeys_any): # Checking if any element of the FileKeys is present in the filename
                r.append(os.path.join(root, name)) # Creating a list of file names
    return r

# I like the version below more!!!!!!!!!
# An alternative to the previous with a for loop
# The output list is given in the order of the FileKeys, which could be very useful if the output will be sensitive to sorting.
# As otherwise it might happen that the output will be in a different order as the FileKeys.
def list_online_files(dir, FileKeys_OL):
    r = []
    for root, dirs, files in os.walk(dir):
        for key in FileKeys_OL:
            for name in files:
                if key in name: # Checking if any element of the FileKeys is present in the filename
                    r.append(os.path.join(root, name)) # Creating a list of file names
    return r

以上是关于python 查找列表中的列表元素的一部分(函数)的主要内容,如果未能解决你的问题,请参考以下文章

怎么查找python列表中元素的位置

如何在python列表中查找某个元素的索引

查找列表中的最小元素(递归) - Python

python如何查找小于9的元素

python 查找数字列表中的多数元素

python切片:使用列表的一部分