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]])
4

5 回答 5

2

将其拆分为“,”,然后排序,然后加入列表:

new_list.append([linewords[0],
                        linewords[1],
                        linewords[3],
                        ",".join(sorted(linewords[4].split(",")))])
于 2013-09-26T10:06:02.653 回答
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
于 2013-09-26T17:20:12.527 回答
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)])
于 2013-09-26T10:13:29.220 回答
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]
于 2013-09-26T10:17:27.047 回答
0
[x[:-1]+[','.join(sorted(x[-1].split(',')))] for x in new_list]
于 2013-09-26T10:32:27.383 回答