比较列并打印越来越大的行

时间:2013-04-03 21:47:05

标签: python unix awk

我有这样的2个文件

文件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)

3 个答案:

答案 0 :(得分:0)

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 

注意:有优化空间。如果表现很关键,你可以考虑(只是建议)

  • sort file1 descending
  • sort file2 ascending
  • 首先从已排序的文件2中获取,从file1.first查看file1,当找到较小的文件时,记录位置/索引x
  • 从排序后的文件2中取得第2个,从file1.x开始比较,当找到正确的文件时,更新x
  • 直到file2结束

蛮力方式将O(mxn)O(nxm)取决于nm哪个更大。

上面的算法......我没有分析,应该比O(mxn) ..;)

更快

python和awk都可以完成这项工作。如果可能,将两个文件加载到内存中。如果你有怪物文件,这是另一个算法问题。例如排序巨大的文件

答案 1 :(得分:0)

将每个文件读入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

答案 2 :(得分:0)

使用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]
相关问题