我已经从 txt
文件中复制了大约 2000
行的 tuples
到 list
中。现在我需要将列表中的每个元素与列表其余部分中的后续元素进行比较,并且我只需要比较每个元素一次,即如果我获取第一个元素并与列表中的每个元素进行比较,那么我可以将其丢弃的比较。我已经成功地做到了这一点,但现在我需要帮助来简化输出。
这是我的比较 block 代码:
R = [(20, 12, 40, 42, 45), (40, 21, 40, 42, 49),
(6, 19, 22, 36, 48), (2, 5, 20, 24, 33),
(8, 12, 24, 28, 44), (3, 15, 29, 30, 37),
(20, 17, 30, 33, 43), (3, 15, 16, 29, 42),
(17, 18, 20, 35, 39), (20, 21, 23, 43, 48),
(14, 24, 30, 40, 45)...]
for lineno1, tup in enumerate(R):
print("")
# iterate over the current tuple
for i, num in enumerate(tup):
# compare every number in the tuple to the rest of the list
for lineno2 in range(lineno1+1, len(R)):
tup2 = R[lineno2]
if num == tup2[i]:
print(f"In line: {lineno1+1} {tup} No. '{num} is found in line {lineno2+1} {tup2}.")
break
这是我的输出:
line: 1 (20, 12, 40, 42, 45) No. 20 is found in line '7' (20, 17, 30, 33, 43).
line: 1 (20, 12, 40, 42, 45) No. 12 is found in line '5' (8, 12, 24, 28, 44).
line: 1 (20, 12, 40, 42, 45) No. 40 is found in line '2' (40, 21, 40, 42, 49).
line: 1 (20, 12, 40, 42, 45) No. 42 is found in line '2' (40, 21, 40, 42, 49).
line: 1 (20, 12, 40, 42, 45) No. 45 is found in line '11' (14, 24, 30, 40, 45).
line: 2 (40, 21, 40, 42, 49) No. 21 is found in line '10' (20, 21, 23, 43, 48).
line: 3 (6, 19, 22, 36, 48) No. 48 is found in line '10' (20, 21, 23, 43, 48).
line: 4 (2, 5, 20, 24, 33) No. 20 is found in line '9' (17, 18, 20, 35, 39).
line: 6 (3, 15, 29, 30, 37) No. 3 is found in line '8' (3, 15, 16, 29, 42).
line: 6 (3, 15, 29, 30, 37) No. 15 is found in line '8' (3, 15, 16, 29, 42).
line: 7 (20, 17, 30, 33, 43) No. 20 is found in line '10' (20, 21, 23, 43, 48).
line: 7 (20, 17, 30, 33, 43) No. 30 is found in line '11' (14, 24, 30, 40, 45).
如您所见,如果我使用 2000 行 元组
,输出可能会失控。我得到了我想要的输出,但我需要一些帮助来清理输出以获得整洁清晰的输出。在上面的输出中,每个 tuple
最多有 5 行输出,如果我正在处理 1000 行数据,这可能需要很多行。我想简化输出,使每个 tuple
都在一行中。
我想要这样的输出:
Line 1: (20, 12, 40, 42, 45) (7, 5, 2, 2, 11) #Right side values are line numbers of the respective element in the tuple
Line 2: (40, 21, 40, 42, 49) (0, 10, 0, 0, 0)
Line 3: (6, 19, 22, 36, 48) (0, 0, 0, 0, 10)
Line 4: (2, 5, 20, 24, 33) (0, 0, 9, 0, 0)
Line 6: (3, 15, 29, 30, 37) (8, 8, 0, 0, 0)
Line 7: (20, 17, 30, 33, 43) (10, 0, 11, 0, 0)
最佳答案
你不能在最后打印 if
,而是存储值。使用 for..else
符号设置 0
for
中没有使用 break循环,仅当至少找到一个值时才打印(可以使用 sum != 0
完成)
for lineno1, tup in enumerate(R):
res = []
for i, num in enumerate(tup):
for lineno2 in range(lineno1 + 1, len(R)):
tup2 = R[lineno2]
if num == tup2[i]:
res.append(lineno2 + 1)
break
else:
res.append(0)
if sum(res) != 0:
print(f"In line: {lineno1 + 1} {tup} {res}.")
CODE DEMO
关于python - 我需要简化当前输出并获得干净的输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63655559/