简体   繁体   中英

How to print two columns alphabetically in python

I have a list where I need to sort in alphabetic order based on two columns. My current code is indeed sorting it in alphabetic order but it is not sorting the persons last time as well. In my code below. I used itemgetter(3) to get the persons first name. But how would I do it in such that I am able to get 2 item getter such as itemgetter(3,4). I hope my questions make sense. Thank you.

note: is it possible to join the first and last name into one string? and then use that one string as the item getter?

My code.

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

My output

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

Output should be

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

You could try:

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))

See also: sorting how-to


(Actually, I think this is indeed correct:
leverages comparison of built-in lists.)
You could then try:

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))

If you put the data in a excel instead of text and the read the excel through Panda libraries then you can sort by multiple columns very easily.

Suppose the data in excel is like this:

在此处输入图像描述

then you can read the data in Panda dataframe and sort:

import pandas as pd

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

I have chosen to sort by column C and D, you can choose whatever columns you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM