0

Using .sort() in Python, how do I sort a 2D list e.g.:

myVar = [['blueberries','fruit','5.20'],['bean sprouts','vegetable','9.25'],['tulip','flower','8.93']]
#added comma

by item e.g.,:

myVar = [['bean sprouts','vegetable','9.25'],['blueberries','fruit','5.20'],['tulip','flower','8.93']]

by price e.g.,:

myVar = [['blueberries','fruit','5.20'],['tulip','flower','8.93'],['bean sprouts','vegetable','9.25']]

where "blueberries, bean sprouts and tulips" are items, "fruit, vegetable and flower" are categories and the floats are prices.

2
  • 1
    Any elements in lists have to be separated by commas. Please don't use list as a variable as it is an inbuilt function Commented Aug 1, 2021 at 9:18
  • 1
    Take a look at the 'sorted' builtin function and, in particular, the [optional] 'key' named parameter Commented Aug 1, 2021 at 9:20

4 Answers 4

1

Do not forget to put commas between the elements of a list

myVar = [['blueberries','fruit','5.20'],
         ['bean sprouts','vegetable','9.25'],
         ['tulip','flower','8.93']]

Now you could use the sorted builtin as Andy Knight suggested in the comments and specify a key function to use for comparing items.

Sort list by price and get a copy of the sorted list

sorted(myVar, key=lambda x: float(x[2]))

Sort list by item name

sorted(myVar, key=lambda x: x[0])
Sign up to request clarification or add additional context in comments.

Comments

1

Consider using something like this:-

myList = [['blueberries', 'fruit', 5.20], [
    'bean sprouts', 'vegetable', 9.25], ['tulip', 'flower', 8.93]]

for i in range(3):
    print(sorted(myList, key=lambda x: x[i]))

Comments

0

You can use lambda

For example,

Sorting by item:

list.sort(key = lambda x: x[0])

Sorting by price:

list.sort(key = lambda x : x[2])

Comments

0

You can use the built-in sorted function:

def Sort(sub_li):
    return(sorted(sub_li, key = lambda x: x[2]))    

sub_li =[['blueberries','fruit','5.20'],['bean sprouts','vegetable','9.25'],['tulip','flower','8.93']]
print(Sort(sub_li))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.