-1

I have a file.txt with the following:

('sim', 'sim','03-01-19', 'sim','Fechada', 'sim')

('ano', 'a', '02-01-19', 'a', 'Aberta', 'a')

('pano', 's', '01-01-19', 's', 'Aberta', 's')

I would like to sort it like this:

('ano', 'a', '02-01-19', 'a', 'Aberta', 'a')

('pano', 's', '01-01-19', 's', 'Aberta', 's')

('sim', 'sim','03-01-19', 'sim','Fechada', 'sim')

also sort it by the date like this:

('pano', 's', '01-01-19', 's', 'Aberta', 's')

('ano', 'a', '02-01-19', 'a', 'Aberta', 'a')

('sim', 'sim','03-01-19', 'sim','Fechada', 'sim')

If anyone could help me with that i would be very grateful :)

Sry for my bad English

def ordenar():
    ficheirocompra = open("compras.txt","r")
    lines = ficheirocompra.readlines()

    for line in lines:
        a = line[0:line.find(',')]
        print(a.sort())

    ficheirocompra.close()
alanjds
  • 3,972
  • 2
  • 35
  • 43

1 Answers1

0

If you already have a list of tuples and want to sort by the first item of each tuple, then .sorted or .sort will do the job. Remember that .sort sorts the list itself, whereas .sorted returns a sorted list.

>>> L = [('sim', 'sim','03-01-19', 'sim','Fechada', 'sim'),
...      ('ano', 'a', '12-01-19', 'a', 'Aberta', 'a'),
...      ('zoom', 'z', '05-01-19', 'z', 'Yo', 'z'),
...      ('pano', 'zz', '01-01-19', 's', 'Aberta', 's')]
>>> L_namesort = sorted(L)
>>> print(L_namesort)
[('ano', 'a', '12-01-19', 'a', 'Aberta', 'a'), ('pano', 'zz', '01-01-19', 's', 'Aberta', 's'), ('sim', 'sim', '03-01-19', 'sim', 'Fechada', 'sim'), ('zoom', 'z', '05-01-19', 'z', 'Yo', 'z')]

Another way to do this is to use the key parameter and pick which item to sort by.

def mysortingkey(item):
    return item[0]

L = [('sim', 'sim','03-01-19', 'sim','Fechada', 'sim'),
     ('ano', 'a', '12-01-19', 'a', 'Aberta', 'a'),
     ('zoom', 'z', '05-01-19', 'z', 'Yo', 'z'),
     ('pano', 'zz', '01-01-19', 's', 'Aberta', 's')]

L_namesort = sorted(L, key=mysortingkey)
print(L_namesort)

You can use this same strategy to sort by date, though this means converting the date string to an actual datetime date. Otherwise a date like "12-25-18" would be considered "later" than "01-03-19".

import datetime

def thedatesort(item):
    return datetime.datetime.strptime(item[2], '%m-%d-%y')

L = [('sim', 'sim','03-01-19', 'sim','Fechada', 'sim'),
     ('ano', 'a', '12-01-19', 'a', 'Aberta', 'a'),
     ('zoom', 'z', '05-01-19', 'z', 'Yo', 'z'),
     ('pano', 'zz', '01-01-19', 's', 'Aberta', 's')]

L_datesorted = sorted(L, key=thedatesort)
print(L_datesorted)
Bill M.
  • 1,388
  • 1
  • 8
  • 16