我使用以下代码加载的数据将以以下格式结束:
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]])