如果您需要list元素作为子列表,那么上面的答案是可以的。
但如果你只需要对结果进行排序with open("Results.txt") as inf:
data = []
for line in inf:
line = line.split()
if len(line)==3:
data.append(tuple(line)) #append as tuple
>>> data #as result of codes
[('5', 'Test', 'b'), ('4', 'Test', 'b'), ('6', 'Test', 'c'), ('7', 'Test', 'a')]
>>> data.sort()
>>> data #ascending order
[('4', 'Test', 'b'), ('5', 'Test', 'b'), ('6', 'Test', 'c'), ('7', 'Test', 'a')]
>>> data.sort(reverse=True)
>>> data # descending order
[('7', 'Test', 'a'), ('6', 'Test', 'c'), ('5', 'Test', 'b'), ('4', 'Test', 'b')]
那你想干什么都行
编辑
^{pr2}$
编辑2.1使用set()避免重复>>> with open('ex4.txt') as inf:
... data = set()
... for line in inf:
... line = line.split()
... if len(line)==3:
... data.add(tuple(line))
...
>>> data
set([('2', 'Test', 'c'), ('0', 'Test', 'a'), ('1', 'Test', 'a'), ('3', 'Test', 'b')])
>>> list(data)
[('2', 'Test', 'c'), ('0', 'Test', 'a'), ('1', 'Test', 'a'), ('3', 'Test', 'b')]
>>>
编辑2.2使用if避免重复记录>>> with open("ex4.txt") as inf:
... data = []
... for line in inf:
... line = line.split()
... if (len(line)==3) and (tuple(line) not in data):
... data.append(tuple(line))
...
>>> data
[('1', 'Test', 'a'), ('2', 'Test', 'c'), ('3', 'Test', 'b'), ('0', 'Test', 'a')]