比较 2 个整数列表

compare 2 lists of integers

我有 2 个这样的 txt 文件:

fileA:      fileB:
0           0   
5           0 
0           80
20          10 
600         34

我需要根据列表中的位置比较这两个列表中的数字。我需要生成一个输出文件,其中包含对每一行的比较,例如:

Output:
E
A
B
A
A

我试过类似的方法:

lineA = [lineb.rstrip('\n') for lineb in open("fileA.txt")]
lineB = [lineb.rstrip('\n') for lineb in open("fileB.txt")]
for i in lineA:
    for u in lineB:
        if lineA[i] > lineB[i]:
           print("A")
        elif lineA[i] < lineB[i]:
           print("B")
        elif lineA[i] == lineB[i]:
           print("E")

但是循环无法正常工作。 我也尝试过首先将列表转换为整数(以防它们无法被识别为 ad int),例如:

for w in range(0, len(lineA)):
    lineA[w] = int(lineA[w])
    print(str(lineA))

但我无法解决问题...

使用内置函数zip并行迭代两个列表:

lineA = [lineb.rstrip('\n') for lineb in open("fileA.txt")]
lineB = [lineb.rstrip('\n') for lineb in open("fileB.txt")]
for a, b in zip(lineA, lineB):
    if a > b:
       print("A")
    elif a < b:
       print("B")
    elif a == b:
       print("E")

您也可以避免一次比较,因为在比较两个数字 ab 时存在三种情况:

  • a 大于 b
  • a小于b
  • a 等于 b
lineA = [lineb.rstrip('\n') for lineb in open("fileA.txt")]
lineB = [lineb.rstrip('\n') for lineb in open("fileB.txt")]
for a, b in zip(lineA, lineB):
    if a > b:
       print("A")
    elif a < b:
       print("B")
    else:
       print("E")

也可以考虑使用 with 打开您的文件,如其他答案中所建议的那样。

您可以使用zip并行遍历两个列表:

# use `with` to automatically close the files after reading
with open("fileA.txt") as file_a, open("fileB.txt") as file_b:
    # use `int` in the list comprehension
    # and, use `.rstrip()` if you just want to remove whitespace
    lineA = [int(line.rstrip()) for line in file_a]
    lineB = [int(line.rstrip()) for line in file_b]

for i, u in zip(lineA, lineB):
    if i > u:
       print("A")
    elif i < u:
       print("B")
    else:
       print("E")

为什么不直接使用 zip 来比较每个数字,并使用 map int 来比较每个文件:

with open("fileA.txt") as file_a, open("fileB.txt") as file_b:
    for a, b in zip(file_a, file_b):
        a, b = map(int, (a, b))
        if a > b:
            print("A")
        elif a < b:
            print("B")
        else:
            print("E")

您可以将 mapzip 一起使用:

def compare(z):
    a, b = z

    if a == b:
        return 'E'

    if a > b:
        return 'A'

    return 'B'

with open("fileA.txt") as file_a, open("fileB.txt") as file_b:
    a_nums = map(int, map(str.rstrip, file_a.readlines()))
    b_nums = map(int, map(str.rstrip, file_b.readlines()))


    for greater in map(compare, zip(a_nums, b_nums)):
        print(greater)

输出:

E
A
B
A
A

要写入输出文件,您可以使用:

with open("fileA.txt") as file_a, open("fileB.txt") as file_b, open("output.txt", 'w') as output:
    a_nums = map(int, map(str.rstrip, file_a.readlines()))
    b_nums = map(int, map(str.rstrip, file_b.readlines()))

    for greater in map(compare, zip(a_nums, b_nums)):
        print(greater, file=output)