-2

So here's my code. I separated the items in the list and printed them:

mylist = [["Orange", "Banana"], ["Grape", "Orange", "Apple"]]

for s in mylist:
print '\n'.join(s)

Orange
Banana
Apple
Grape
Orange

But I want the list alphabetized. I've tried this, but it only sorts the items within their nests:

for s in mylist:
print '\n'.join(sorted(s))

Banana
Orange
Apple
Grape
Orange

How do you print and sort items in a nested list all together?

1 Answers1

1

Basically it's combining flattening and sorting. Flattening is handled in various ways here: Making a flat list out of list of lists in Python. Sorting is built-in.

My version:

chain using itertools.chain then sort:

import itertools

for i in sorted(itertools.chain.from_iterable(mylist)):
    print(i)

Or without itertools, generate a list comprehension (which has the benefit of passing a list to sorted so sorted doesn't need to force iteration):

for i in sorted([x for sl in mylist for x in sl]):
    print(i)

(the most efficient way would probably be sorted(list(itertools.chain.from_iterable(mylist))), though)

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219