sorting a list of tuples based on date - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: sorting a list of tuples based on date (/thread-12117.html) |
sorting a list of tuples based on date - bluefrog - Aug-09-2018 Hi I am unsure whether the tuple is sorted or not. There appears to be no difference to the list of tuples after being sorted. #!/usr/bin/python3 import operator from datetime import datetime phones = [('Samsung S7', '11 March 2016'), ('Samsung S8','29 March 2017'), ('Samsung S9', '16 March 2018'), ('Google Pixel', '20 October 2016'),('Google Pixel 2', '21 October 2017'), ('Apple iPhone 7', '7 September 2016'),('Apple iPhone 8','1 September 2017'),('Apple iPhone 9', '12 September 2018')] def get_key(phone_record): return datetime.strptime(phone_record[1], '%d %B %Y') print("Before sorting\n", phones) sorted(phones, key=get_key) print("\nAfter sorting\n", phones)The output is as: Before sorting [('Samsung S7', '11 March 2016'), ('Samsung S8', '29 March 2017'), ('Samsung S9', '16 March 2018'), ('Google Pixel', '20 October 2016'), ('Google Pixel 2', '21 October 2017'), ('Apple iPhone 7', '7 September 2016'), ('Apple iPhone 8', '1 September 2017'), ('Apple iPhone 9', '12 September 2018')] After sorting [('Samsung S7', '11 March 2016'), ('Samsung S8', '29 March 2017'), ('Samsung S9', '16 March 2018'), ('Google Pixel', '20 October 2016'), ('Google Pixel 2', '21 October 2017'), ('Apple iPhone 7', '7 September 2016'), ('Apple iPhone 8', '1 September 2017'), ('Apple iPhone 9', '12 September 2018')]Any ideas how I can view the sorted phone list ? RE: sorting a list of tuples based on date - Vysero - Aug-09-2018 Sure, sorted() as your using it generates a new list without altering the old one so try: import operator from datetime import datetime phones = [('Samsung S7', '11 March 2016'), ('Samsung S8','29 March 2017'), ('Samsung S9', '16 March 2018'), ('Google Pixel', '20 October 2016'),('Google Pixel 2', '21 October 2017'), ('Apple iPhone 7', '7 September 2016'),('Apple iPhone 8','1 September 2017'),('Apple iPhone 9', '12 September 2018')] def get_key(phone_record): return datetime.strptime(phone_record[1], '%d %B %Y') print("Before sorting\n", phones) sorted(phones, key=get_key) print("\nAfter sorting\n", phones) x = sorted(phones, key= get_key) print(x) RE: sorting a list of tuples based on date - ichabod801 - Aug-10-2018 To sort a list in place, use the sort method of the list ( phones.sort(key = get_key) ).
|