【问题标题】:how do i sort a file second column in python code [duplicate]我如何在python代码中对文件第二列进行排序[重复]
【发布时间】:2020-07-11 08:53:34
【问题描述】:

这是我的文本文件。我想按升序对第二列进行排序。如何在 python 代码中对其进行排序?

测试文件内容:

ghj sfs
dtj fsf
zzz hdh
abc kdk
bcd jdd
csf jkd
sfa aaa
ser jld
afr zzz
awr kld
fas ljl
afr lfl
faw kks

【问题讨论】:

  • 将其作为 pandas 数据框读取并使用sort_values() 对其进行排序。这回答了你的问题了吗? how to sort pandas dataframe from one column
  • 1. 读取文件内容。 2. 使用带有自定义key 参数的sorted() 对行进行升序排序。 3. Re*(?)*写入结果。
  • 熊猫方法是否只是对列进行排序的选项?您提到的文本文件与我的问题相同。我不知道 pandas 的概念来编写程序。有没有任何选项可以在 python 中对列进行排序?
  • 您可能会考虑接受答案以奖励那些对您有帮助的人,或者至少发表评论以解释缺少的内容;)

标签: python command-line


【解决方案1】:

你可以这样做

# Read
with open("filename.txt") as fic:
    lines = [line.rstrip().split() for line in fic] # read each line

# Sort
lines = sorted(lines, key=lambda x:x[1])

# Write again
with open("filename.txt", "w") as fic:
    fic.writelines([" ".join(line) + "\n" for line in lines]) # write each line

其他阅读方式

lines = []
with open("filename.txt") as fic:
     for line in fic:
        line = line.rstrip().split()
        lines.append(line)

其他写法

with open("filename.txt", "w") as fic:
    for line in lines:
        fic.write(" ".join(line) + "\n")

【讨论】:

  • 它工作正常。谢谢。你能解释一下下面提到的两行....
  • lines = [line.rstrip().split() for line in fic]
  • fic.writelines([" ".join(line) + "\n" for line in lines])
  • @ChezhiyanSTR 即每行只读写
  • 我知道有两行是读写的。我不知道那几行……你能扩展这两行吗?
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
相关资源
最近更新 更多