python如何在文本内排序_在python中对文本文件中的项进行排序

如果您需要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')]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值