0

I need to sort a list with a note to it.

For instance:

list = ['2015-12-01: remember groceries' , '2017-12-21 : buy presents'] etc.

My problem is that I need to sort the list by the dates and still have the notes attached to that date. Any ideas how to do this? Dictionary? Lists within lists?

I know how to sort just the dates, but I can't seem to figure out how to sort it with the notes attached to it.

DavidG
  • 24,279
  • 14
  • 89
  • 82
  • Possible duplicate of [How can I sort a dictionary by key?](https://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key) – jimf Dec 18 '17 at 09:17
  • Doesn't `sort(list)` do exactly what you are asking? – tripleee Dec 18 '17 at 09:28
  • 2
    (Don't call your variable `list`, though.) – tripleee Dec 18 '17 at 09:28
  • You could use numpy argsort to retrieve the indices, then apply those indices to several arrays containing your different data types. –  Dec 18 '17 at 10:12
  • Dates given in `YYYY-MM-DD` format can be sorted chronologically as strings using `sorted()`. It is when you have `DD-MM-YYYY` or other formats that the problems start. – Martin Evans Dec 18 '17 at 11:30

3 Answers3

3

Assuming that your data all look like this:

  • Every entry in the array is a string
  • Every entry begins with the date in the format 'YYYY-MM-DD'

Then you could do simply do

list.sort();

This would sort the strings in your array lexicographically, and for dates in the above format this is equivalent to sorting them in the normal time line. This would not work if your dates also have other formats like 'YYYY-M-DD'.

GaloisGecko
  • 196
  • 5
1

Your date presentation is sortable as is. just

res = sorted(list)
splash58
  • 26,043
  • 3
  • 22
  • 34
0

just go for a list of tuples. this is always sorted by the first element and you can get your date value and your note separately

list = [('2015-12-01', 'remember groceries') , ('2017-12-21', 'buy presents'), ('2015-12-21', 'xxx')]
print(sorted(list))
print(list[0][1], list[1][1])
jan-seins
  • 1,253
  • 1
  • 18
  • 31