我有3个文本文件:
列表1.txt:
032_M5, 5
035_M9, 5
036_M4, 3
038_M2, 6
041_M1, 6
列表2.txt:
032_M5, 6
035_M9, 6
036_M4, 5
038_M2, 5
041_M1, 6
List3.txt文件:
032_M5, 6
035_M9, 6
036_M4, 4
038_M2, 5
041_M1, 6
其中所有3个文本文件中的行的第一部分(即字符串)相同,但第二部分(即编号)更改。你知道吗
我想从中得到三个输出文件:
Output1.txt-->;数字对应字符串的所有行都不同。 示例:
036_M4 3, 5, 4
Output2.txt-->;数字对应字符串的所有行都相同。 示例:
041_M1, 6
Output3.txt-->;至少两个数字对应于一个字符串的所有行都相同(这也包括Output2.txt的结果)。 示例:
032_M5, 6
035_M9, 6
038_M2, 5
041_M1, 6
然后我需要Output3.txt中包含数字1、数字2、数字3、数字4、数字5和数字6的行数。你知道吗
这是我试过的。它给了我错误的输出。你知道吗
from collections import defaultdict
data = defaultdict(list)
for fileName in ["List1.txt","List2.txt", "List3.txt"]:
with open(fileName,'r') as file1:
for line in file1:
col1,value = line.split(",")
data[col1].append(int(value))
with open("Output3.txt","w") as output:
for (col1),values in data.items():
if len(values) < 3: continue
result = max(x for x in values)
output.write(f"{col1}, {result}\n")
这是一种不使用任何python模块的方法,它完全依赖于本机内置的python函数:
上述结果将是:
max
给出列表中最大的数字,而不是最常出现的数字。为此,请使用statistics.mode
相关问题 更多 >
编程相关推荐