how to get vairable to sort with list? - 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: how to get vairable to sort with list? (/thread-15180.html) |
how to get vairable to sort with list? - DouTh - Jan-07-2019 analyst = list([304, 213, 175, 379, 572, 801, 630]) print(list(analyst)) print(sorted(analyst)) analyst[0] = "Monday " analyst[1] = "Tuesday " analyst[2] = "Wednesday " analyst[3] = "Thursday " analyst[4] = "Friday " analyst[5] = "Saturday " analyst[6] = "Sunday " print(list(analyst)) print(sorted(analyst)) # i am trying to get two types of information, first the list from monday - sunday with numbers from each day # the secound print i am trying to get the list with numbers sorted from lowest to highest and the variable with string sorted from lowest to highest # i get the variable to go from a - z in order but i want them to follow the same order as the list RE: how to get vairable to sort with list? - buran - Jan-07-2019 Note that what you do is to replace the values in the original list, i.e. you have lost the numbers. values = list([304, 213, 175, 379, 572, 801, 630]) weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] # data as list of tuples data = list(zip(values, weekdays)) print(sorted(data)) print('\n\n') data = list(zip(weekdays, values)) print(sorted(data, key=lambda x: x[1])) print('\n\n') from operator import itemgetter print(sorted(data, key=itemgetter(1))) print('\n\n') # data as dict data = dict(zip(weekdays, values)) print(sorted(data.items(), key=lambda x: x[1])) # or alternatives print(dict(sorted(data.items(), key=lambda x: x[1]))) # as of 3.7 order of insertion of dict elements is preserved print(sorted(data.items(), key=itemgetter(1))) print(dict(sorted(data.items(), key=itemgetter(1)))) print('\n\n') # now going fancy with namedtuple from collections from collections import namedtuple Record = namedtuple('Record', ['day', 'value']) data = [Record(day, value) for day, value in zip(weekdays, values)] print(sorted(data, key=lambda x: (x.value, x.day)))
|