【问题标题】:How to print two columns alphabetically in python如何在python中按字母顺序打印两列
【发布时间】:2020-07-30 18:45:50
【问题描述】:

我有一个列表,我需要根据两列按字母顺序排序。我当前的代码确实按字母顺序对其进行了排序,但上次也没有对人员进行排序。在我下面的代码中。我使用 itemgetter(3) 来获取人员的名字。但是我将如何做到这一点,以便我能够获得 2 个项目吸气剂,例如 itemgetter(3,4)。我希望我的问题是有意义的。谢谢。

注意:是否可以将名字和姓氏连接成一个字符串?然后使用那个字符串作为 item getter?

我的代码。

def sortAlpha():
    newFile = open("ScriptTesting3.txt","w")
    def csv_itemgetter(index, delimiter=' ', default=''):
        def composite(row): 
            try:
                return row.split(delimiter)[index]
            except IndexError:
                return default
        return composite

    with open("ScriptTesting2.txt", "r") as file:
         for eachline in sorted(file, key=csv_itemgetter(3)):
             print(eachline.strip("\n") , file = newFile)

ScriptTesting2.txt

2312 filand    4 Joe  Alex
4541 portlant  4 Alex Gray
5551 highlands 4 Alex Martin

我的输出

5551 highlands 4 Alex Martin
4541 portlant  4 Alex Gray 
2312 filand    4 Joe  Alex 

输出应该是

5551 highlands 4 Alex Gray 
4541 portlant  4 Alex Martin 
2312 filand    4 Joe  Alex

【问题讨论】:

  • 你可以在问题中添加文本文件的内容吗?
  • @Anand 我刚刚做了。

标签: python csv sorting alphabetical


【解决方案1】:

你可以试试:

from operator import itemgetter

...

with open("ScriptTesting2.txt", "r") as file:
  lines = file.readlines()
linesSplit = [l.split() for l in lines]
linesSplitSorted = sorted(linesSplit, key=itemgetter(3, 4))
for l in linesSplitSorted: print(' '.join(l))

另请参阅:sorting how-to


(其实我觉得这确实是对的:
利用内置列表的比较。)
然后你可以试试:

def itemGetterRest(idx):
  def helper(seq):
    return seq[idx:]
  return helper

with open("Input.txt", "r") as file:
  lines = file.readlines()
linesSplit = [l.split() for l in lines]
linesSplitSorted = sorted(linesSplit, key=itemGetterRest(3))
for l in linesSplitSorted: print(' '.join(l))

【讨论】:

  • 我没有包含整个数据,这只是一个示例。因为我做了 itemgetter(3,4)。如果没有姓氏怎么办?有什么办法可以在 3 点之后采取任何措施吗?喜欢 key = itemgetter(3:)
  • 嗯,不确定,需要再检查一下。
【解决方案2】:

如果您将数据放入 excel 中而不是文本中,并通过 Panda 库读取 excel,那么您可以非常轻松地按多列排序。

假设excel中的数据是这样的:

然后你可以读取 Panda 数据框中的数据并排序:

import pandas as pd

data = pd.read_excel('ScriptTesting3.xlsx')
data = data.sort_values(by=['C','D'], ascending=True)
print(data)

我选择了按C列和D列排序,你可以选择任何你想要的列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2018-06-07
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多