在Parse之后比较目录中的两个列表

时间:2016-12-14 20:53:02

标签: python python-2.7 parsing

我创建了一个函数,它将解析目录中的文件并将值保存在列表中。然后我在三个不同的目录上运行该函数。一旦我这样做,我就想比较列表,看看它们是否相等。但是,即使我在每个目录中复制并粘贴相同的文件,执行此操作的功能始终返回False。以下是我正在使用的两个功能。

ParseFiles功能

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)

比较Parse

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")

1 个答案:

答案 0 :(得分:1)

由于您的第一次检查是列表长度相同,因此您可以避免在此处比较列表d的问题。

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)