我有这样一个文件:
x 48012 F 1.000
x 48169 R 0.361
x 87041 R 0.118
x 9032 R 0.176
x 9150 R 0.521
我想根据第 1,2 列和第 3 列是否相同来过滤掉结果文件中具有唯一值的行 - 第 2 列的容差为 +/- 200。 例如前两行
x 48012 F 1.000
x 48169 R 0.361
会变成
x 48012 F 1.000
因为 48169-48012 是 157,在±200 范围内
总的来说,最终文件是
x 48012 F 1.000
x 87041 R 0.118
x 9032 R 0.176
我试过了
out=open('result.txt', 'w')
my_file= open('test.txt', 'r')
seen = set()
for line in my_file:
line=line.strip().split('\t')
if line[0]==seen[0] and line[2]==seen[2] and ((int(line[1])==int(seen[1]-200)) or (int(line[1])==(seen[1]-200))):
out.write(line)
但是集不能被索引
请您参考如下方法:
在这里使用 Set 没有意义,因为您必须将元素分解为标记,这样管理起来就很麻烦。我会使用一对二维数组,一个用于候选行,一个用于结果。
我会将整个文件读入候选数组并创建一个空结果数组。然后我将遍历 candidates 数组并在结果数组中查找匹配项。如果我没有在结果数组中找到匹配项,我会将候选人复制到结果数组中。
类似于:
candidates = []
results = []
for line in my_file:
candidates.append(line.split('\t'))
for line in candidates:
seen = false
for possible_match in results:
if matching_line(possible_match, line):
seen = true
if seen:
continue
else:
results.append(line)
那么你需要一个函数来判断两个数组是否匹配:
function matching_line(array1, array2):
if array1[0] = array2[0]
..etc
