2013-09-26 86 views
0

的數據我用下面的代碼加載將在以下格式結束:排序列表元素的字母順序

new_list = [['1', '100', 'A', 'B,A'], ['2', '200', 'A', 'T'], 
['3', '200', 'H', 'A,C'], ['4', '300', 'W', 'T'], 
['5', '400', 'I', 'BABA,ABB'], ['6', '500', 'Q', 'LP,AL']] 

我想實現的是分類的最後一列的字母順序更改列表:

new_list = [['1', '100', 'A', 'A,B'], ['2', '200', 'A', 'T'], 
['3', '200', 'H', 'A,C'], ['4', '300', 'W', 'T'], 
['5', '400', 'I', 'ABB,BABA'], ['6', '500', 'Q', 'AL,LP']] 

但是我不知道如何只對這個列表中的指定索引進行排序。 我應該拆分最後一列,嗎?

的樣本數據:

# Data 
# I 
# don't 
# need 
1 100 982 A B,A 41 
2 200 982 A T 42 
3 200 982 H C 43 
4 300 982 W T 43 
5 400 982 I BABA,ABB 44 
6 500 982 Q LP,AL 44 

加載數據:

filename = 'test.txt' 

new_list = [] 

readFile = open(filename, 'r') 
lines = readFile.readlines() 
for line in lines: 
    if not line[0].startswith('#'): 
     linewords = line.split() 
     new_list.append([linewords[0], 
         linewords[1], 
         linewords[3], 
         linewords[4]]) 

回答

2

分裂它 「」,然後排序,再加入列表:

new_list.append([linewords[0], 
         linewords[1], 
         linewords[3], 
         ",".join(sorted(linewords[4].split(",")))]) 
0

第一次分裂,然後排序,最後加入。可能有多個空格,你可以使用正則表達式分割。

import re 
p = re.compile(' +') 

for line in lines: 
    if line.startswith('#'): 
     continue 
    linewords = p.split(line) 
    lastword = linewords[4].split(',') 
    lastword.sort() 
    new_list.append([linewords[0],linewords[1],linewords[3],','.join(lastword)]) 
0

嘗試:

def sort_last(inner_list): 
    last = inner_list[-1].split(',') 
    last.sort() 
    last = ','.join(last) 
    return inner_list[:-1] + [last] 

new_list = [sort_last(l) for l in new_list] 
0
[x[:-1]+[','.join(sorted(x[-1].split(',')))] for x in new_list] 
0

試試這個

list2 = [] 

for level1 in new_list: 
    _temp = [] 
    for level2 in level1: 
     if "," in level2: 
      _temp.append(sorted(level2.split(","))) 
     else: 
      _temp.append(level2) 
    list2.append(_temp) 

print list2