按字母顺序对列表元素进行排序

时间:2013-09-26 09:51:07

标签: python sorting python-2.7

我使用以下代码加载的数据最终将采用以下格式:

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

5 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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)])

答案 2 :(得分: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]

答案 3 :(得分:0)

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

答案 4 :(得分: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
相关问题