2017-08-31 70 views

回答

0

我的解決方案是創建這樣的元組列表(一個元組每條線):

(data_in_column_of_interest, entire_line) 

data_in_column_of_interest是任何數據類型,entire_line是字符串。

然後就對這個文件列表:包含文件:

def sortLinesByColumn(readable, column, columnt_type): 
    """Returns a list of strings (lines in readable file) in sorted order (based on column)""" 
    lines = [] 

    for line in readable: 
     # get the element in column based on which the lines are to be sorted 
     column_element= columnt_type(line.split(',')[column-1]) 
     lines.append((column_element, line)) 

    lines.sort() 

    return [x[1] for x in lines] 


with open('G:/Ftest/data.txt') as f: 
    # sort the lines based on column 1, and column 1 is type int 
    sorted_lines = sortLinesByColumn(f, 1, int) 

    for l in sorted_lines: 
     print(l) 

輸入

1, Bob, 123 
5, Mary, 112 
0, Allen, 2421 
1, lucy, 341 

輸出:一個字符串列表:

0, Allen, 2421 
1, Bob, 123 
1, lucy, 341 
5, Mary, 112 
相關問題