Python Forum
Sorting list of lists with string and int
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting list of lists with string and int
#6
(May-07-2018, 05:38 AM)buran Wrote: actually, the easiest way would be to add sorted to your line 5 list comprehension

a = [sorted(input().split()) for i in range(n)]
this way you always get the number as element with index 0 because when sorting '0' to '9' always go before 'A'

def parse_data(item):
    return (int(item[0]), item[1])


data = ['red 10', '10 blue', 'green 7']
data = [parse_data(sorted(item.split())) for item in data]
output = [cup for radius, cup in sorted(data)]
print('\n'.join(output))
note that sample output in your assignment is NOT correct

It is correct because if it's in the format number color, then number need to be divided by 2 so it will be 5.

(May-06-2018, 02:26 PM)Gribouillis Wrote:
(May-06-2018, 11:42 AM)Otbredbaron Wrote: Why do we need to be explicit and write except ValueError?
I'm not sure I understand exactly what you mean, but here I know that if i[1] contains anything that is not convertible to an integer the call to int() will raise ValueError. In such a case, I always catch the exact exception because I don't want to catch anything else. For example if for some reason there is no i[1], python will throw KeyError and I don't want to catch this at this point. For debugging purposes, it is always better to let unexpected exceptions propagate.

I see now, I need to get used to this try except thing.
Reply


Messages In This Thread
RE: Sorting list of lists with string and int - by Otbredbaron - May-07-2018, 05:54 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need help with sorting lists as a beginner Realist1c 1 828 Apr-25-2023, 04:32 AM
Last Post: deanhystad
  List all possibilities of a nested-list by flattened lists sparkt 1 1,008 Feb-23-2023, 02:21 PM
Last Post: sparkt
  user input values into list of lists tauros73 3 1,180 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,179 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,788 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  List Sorting Problem ZZTurn 5 1,454 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  Sorting List finndude 9 2,601 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  How to efficiently average same entries of lists in a list xquad 5 2,244 Dec-17-2021, 04:44 PM
Last Post: xquad
  sorting a list of lists by an element leapcfm 3 2,005 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  Generate a string of words for multiple lists of words in txt files in order. AnicraftPlayz 2 2,929 Aug-11-2021, 03:45 PM
Last Post: jamesaarr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020