python - How to sort list within a list? -
this question has answer here:
i want sort list based on first item such as:
fruits = \ [['mango', 6, 5, 8.0], ['banana', 2.0, 5, 8.9, 7], ['pineapple', 4, 6.8, 9], ['apple', 3.9, 6, 7, 2]]
to sorted out this:
fruits = \ [['apple', 3.9, 6, 7, 2], ['banana', 2.0, 5, 8.9, 7], ['mango', 6, 5, 8.0], ['pineapple', 4, 6.8, 9]]
i know have use sort()
function don't know how use in right way produce outputs want.
what problem exactly? sort()
sorts first element.
in [14]: fruits = [["mango", 6,5,8.0], ["banana", 2.0,5,8.9,7], ["pineapple", 4,6.8,9], ["apple", 3.9,6,7,2]] in [15]: fruits.sort() in [16]: fruits out[16]: [['apple', 3.9, 6, 7, 2], ['banana', 2.0, 5, 8.9, 7], ['mango', 6, 5, 8.0], ['pineapple', 4, 6.8, 9]]
if items classes or variables, should implement comparison methods (__ge__
, __le__
, __gt__
, __lt__
) accordingly sorting needs.
keep in mind fruits.sort()
modifies list in place, if want new sorted copy, use sorted(fruits)
Comments
Post a Comment