简体   繁体   中英

Sorting tuple genereated by list comprehension in python

I'm having trouble sorting individual tuple created by a list comprehension. Say we have:

words = [(a, b, c) for a in al for b in bl for c in cl]

Now I want to sort each tuple (a, b, c) by doing:

map(lambda x: sorted(x), words)

which gives me the error: 'tuple' object is not callable.

I also tried:

for i in range(len(words)):
    out = [words[i][0], words[i][1], words[i][2]]
    print out.sort()

which prints a bunch of Nones.

What am I missing? Thanks in advance.

You could just sort the tuples as part of the creation:

words = [sorted((a, b, c)) for a in al for b in bl for c in cl]

Note that this will give you a list of lists, not a list of tuples, because sorted returns a list. If you really want tuples you'll have to do

words = [tuple(sorted((a, b, c))) for a in al for b in bl for c in cl]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM