2

我对 python 比较陌生,我发现它很有用,因为我确实需要定期从大型 csv 文件中查找值,因此我尝试使用它。

This is my csv file:
Name, Tag, Size, Height1, Height2,
Name1, B1, 244,42798,5900
Name2, B4, 200,22798,2234
Name3, B5, 240,25798,2745
Name4, B7, 220,32798,4590

我试图使用这段代码,但我仍然把它们弄乱了。

import csv
input = open('file.csv','r')
number_top_values =  raw_input(‘How many top values you need to find?’) #number of top values
file = csv.reader(input)
line1 = file.next()
height = [(row[3],(row[4])) for row in file]
height.sort(key = lambda x: x[1])
height.reverse()
height = height[:number_top_values]
print height

我需要在列中找到 Height1 和 Height2 的最高值(前 2 或前 3 等取决于我需要找到多少最高值)并获得具有这些最高值的整行。任何建议或可能的答案都会有很大帮助。谢谢。

4

2 回答 2

2

您目前正在使用这个:

height = [(row[3],(row[4])) for row in file]
height.sort(key = lambda x: x[1])
height.reverse()

在第一行,您删除了一些您需要的数据(因为您需要整行)。通过对第二行的修改,可以使第三行变得多余。一起:

height = list(file)
height.sort(key=lambda x: int(x[3]), reverse=True)

这样排序Height1。如果要排序Height2,请更改34。如果你想对一个然后另一个排序,你可以排序两次或者做一些更棘手的事情:

height.sort(key=lambda x: (int(x[3]), int(x[4])), reverse=True)
于 2012-10-01T04:32:17.223 回答
1

主要是icktoofay所说的:)

工作代码:

import csv
inputfile = open('file.csv','r')
#don't forget int() to convert input to integer for slicing
while(True):
    try:
        number_top_values =  int(raw_input('How many top values you need to find?')) #number of top values
    except ValueError:
        print "Invalid input! Please try again"
    else:
        break
csvfile = csv.reader(inputfile)
height = list(csvfile)[1:] #exclude first line for labels
height1 = sorted(height, key = lambda x: int(x[3]), reverse=True)[:number_top_values]
height2 = sorted(height, key = lambda x: int(x[4]), reverse=True)[:number_top_values]
# or height.sort(key = lambda x: (int(x[3]),int(x[4])), reverse=True) for double sort
print height1
print height2
inputfile.close()
于 2012-10-01T04:53:21.040 回答