从目录解析后比较两个列表

2024-06-16 16:52:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个函数,可以解析目录中的文件并将值保存在列表中。然后在三个不同的目录上运行函数。一旦我这样做了,然后我想比较一下名单,看看他们是否相等。但是,这样做的函数总是返回False,即使我在每个目录中复制和粘贴相同的文件。下面是我正在使用的两个函数。你知道吗

解析文件功能

def ParseFiles(path):
    for filename in os.listdir(path):
        # check filename to ensure it ends in appropriate file extension
        if filename.endswith(('.cfg', '.startup', 'confg')):
            # concatinate os path and filename
            file_name = os.path.join(path, filename)
            with open(file_name, "r") as in_file:
                for line in in_file:
                    # match everything after hostname
                    match = re.search('^hostname\s(\S+)$', line)
                    #store match in a list for use later
                    if match:
                        hostname = [match.group(1)]
                        return hostname
                        #print (hostname)

比较分析:

def ParseCompare(L1, L2):
    if len(L1) != len(L2):
        return False
    for val in L1:
        if val in L2:
            return False   
    return True

测试解析

archiveParse = ParseFiles(TEST_PATH)
startupParse = ParseFiles(TEST_PATH_1)
runningParse = ParseFiles(TEST_PATH_2)

print ParseCompare(startupParse, archiveParse)

if ParseCompare(startupParse, archiveParse) == False:
    print("Startup does not match Archive")
if ParseCompare(startupParse, runningParse) == False:
    print("Startup and Running do not match")
if ParseCompare(runningParse, archiveParse) == False:
    print("Running does not match Archive")
else:
    print("Compared OK")

Tags: path函数infalseforreturnifmatch
1条回答
网友
1楼 · 发布于 2024-06-16 16:52:42

由于您的第一个检查是列表的长度相同,因此在这里比较listd可以避免这个问题。你知道吗

a = [1, 2, 3]
b = [3, 2, 1]
c = [4, 2, 3]
d = [3, 3, 2, 1]

# Long version
def compare(L1, L2):
    """
    Create a list of booleans for every item, and only return True
    if *all* items in L1 are in L2
    """
    print("comparison lists are {} and {}".format(L1, L2))
    print("Boolean list is {}".format([item in L1 for item in L2]))

    if all(item in L1 for item in L2):
        print('Equal lists')
        return True

    print ('Not equal')
    return False

call1 = compare(a, b)
print "Bool value is: {}".format(call1)
print "..............."

call2 = compare(c, a)
print "Bool value is: {}".format(call2)
print "..............."

call3 = compare(a, d)
print "Bool value is: {}".format(call3)
print "..............."


# Short function
def compare(L1, L2):
    return all(item in L1 for item in L2)

相关问题 更多 >