我有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))
但是我无法解决问题...
答案 0 :(得分:2)
您可以使用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")
答案 1 :(得分:0)
使用内置函数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")
您也可以避免一次比较,因为比较两个数字a
和b
时有三种情况:
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
来打开文件,如其他答案中所述。
答案 2 :(得分:0)
为什么不只使用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")
答案 3 :(得分:0)
您可以将map
与zip
一起使用:
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)