【问题标题】:sort lines in file by negative value in string按字符串中的负值对文件中的行进行排序
【发布时间】:2020-12-13 14:44:06
【问题描述】:

我有以下几行的文件

channel: 6372225 rxLev: -58 name: Right
channel: 6372235 rxLev: -52 name: left 
channel: 4372225 rxLev: -51 name: left 
channel: 1372225 rxLev: -22 name: left 
channel: 6371115 rxLev: -33 name: Right
channel: 6376665 rxLev: -40 name: left 
channel: 6322225 rxLev: -60 name: left 
channel: 6112225 rxLev: -80 name: up

我如何使用 python 通过 rxLev 值对同一文件中的这些行进行排序?

【问题讨论】:

标签: python


【解决方案1】:

假设文件名是stackoverflow.txt

with open('stackoverflow.txt', 'r') as f:
  sorted_list = sorted([item.split(" ") for item in f.readlines()], 
                        key=lambda x: float(x[3]))  # or int

with open('stackoverflow.txt', 'w') as f:
  for sublist in sorted_list:
    f.write(" ".join(word for word in sublist))

【讨论】:

    【解决方案2】:

    您可以简单地读取内容,对其进行排序并在删除旧内容的同时将其写回:

    with open('your_file.txt', 'r+') as f:
        sorted_contents =  ''.join(sorted(f.readlines(), key = lambda x: int(x.split(' ')[3])))
        f.seek(0)
        f.truncate()
        f.write(sorted_contents)
    

    与打开一次读取然后再次写入相比,以原子方式执行它也使其更具抗错性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      • 2015-11-27
      • 2022-11-25
      • 1970-01-01
      • 2021-08-25
      • 2014-05-18
      • 2018-07-02
      相关资源
      最近更新 更多