我有两个这样的文件
文件1有1行:
6
4
13
25
35
50
65
75
and so on.....
file2中有1行
24
45
76
and so on.....
我想获取file2中的每个值(一次一个),并与file1进行比较,如果file1的值小于该数字,则获取这些值并将其保存在列表中,然后根据数字对它们进行排序并打印最大值
例如:我在file2中取24个数字,并与file1进行比较,发现6,4和13在该数字之下,然后我提取它们,将其保存在列表中,并对其进行排序并打印最大值(即13)。
发布于 2013-04-03 22:18:38
将每个文件读入list
,并将每一行转换为int
。然后对两个列表进行排序,以使我们能够高效地迭代,
file1 = sorted([int(l) for l in open('file1.txt').read().split()])
file2 = sorted([int(l) for l in open('file2.txt').read().split()])
i = 0
for file2_number in file2:
while i+1 < len(file1) and file1[i+1] < file2_number:
i += 1
print file1[i]
这当前打印答案(13 35 75
),但如果需要,您可以很容易地修改它以返回list
。
发布于 2013-04-03 22:09:50
awk解决方案:
awk 'NR==FNR{a[$0];next} {b[FNR]=$0}
END{
n=asort(b)
for(j in a)
for(i=n;i>0;i--)
if(b[i]<j){
print "for "j" in file2 we found : "b[i]
break
}
}' file2 file1
输出:
for 45 in file2 we found : 35
for 76 in file2 we found : 75
for 24 in file2 we found : 13
注意::还有优化的空间。如果性能很关键,你可以考虑(只是建议)
首先,当您找到较小的位置/索引时,记录descending
x
x
file1.x
end of file2暴力破解的方式是采用O(mxn)
还是O(nxm)
,这取决于n
和m
哪个更大。
上面的算法。我没有分析,应该比O(mxn)
快..;)
python和awk都可以完成这项工作。如果可能,将这两个文件加载到内存中。如果你有怪物文件,那就是另一个算法问题。例如,对大文件进行排序
发布于 2013-04-03 22:20:47
使用Python,首先将file1中的所有行和file2中的所有行读取到两个单独的列表中,然后您可以简单地遍历它们,将文件1中的每个数字与file2中的每个数字进行比较,如下所示:
#First load each of the lines in the data files into two separate lists
file1Numbers = [6, 4, 13, 25, 35, 50, 65, 75]
file2Numbers = [24, 45, 76]
extractedNumbers = []
#Loops through each number in file2
for file2Number in file2Numbers:
#Loops through each number in file
for file1Number in file1Numbers:
#Compares the current values of the numbers from file1 and file2
if (file1Number < file2Number):
#If the number in file1 is less than the number in file2, add
#the current number to the list of extracted numbers
extractedNumbers.append(file1Number)
#Sorts the list of extracted numbers from least to greatest
extractedNumbers.sort()
#Prints out the greater number in the list
#which is the number located at the end of the sorted list (position -1)
print extractedNumbers[-1]
https://stackoverflow.com/questions/15798779
复制相似问题