[Tutor] Bundle help!
Bill Burns
billburns at pennswoods.net
Tue Jul 10 04:00:28 CEST 2007
[Sara Johnson]
> Sorry to be so confusing. Just realized a dumb mistake I made. It
> doesn't need to be resorted alphabetically and numerically. I need one
> list alphabetical and one numerical.
>
>
> (Alphabetical) List 1, [('Fred', 20), ('Joe', 90), ('Kent', 50),
> ('Sara', 80)]
>
> (Numerical) List 2, [('Fred', 20), ('Kent', 50), ('Sara', 80) ('Joe', 90)]
>
<snip>
I didn't keep track of the thread very well, so I don't know if you have
one single list or two separate lists?? I'll assume you have a single
list and you want to create two new lists sorted differently:
<code>
# Single 'Master List'.
masterList = [('Sara', 80), ('Kent', 50), ('Joe', 90), ('Fred', 20)]
# Create a list for our alpha sort.
alphaList = list(masterList)
# Simply calling sort() will sort it alphabetically.
alphaList.sort()
print 'Alphabetical List: ', alphaList
def sortByNum(tup):
# Helper function.
return tup[1]
# Create a list for our numerical sort.
numList = list(masterList)
# sort() can take an optional key parameter, which allows us to define
# our own sorting method. This sort() calls the sortByNum() function,
# which I've defined to only look at the 2nd item in the tuple (the
# numerical portion.
numList.sort(key=sortByNum)
print 'Numerical List: ', numList
# Or you could also use a lambda in place of the separate
# function def, which would eliminate sortByNum() completely.
#~ numList.sort(key=lambda tup: tup[1])
#~ print 'Numerical List: ', numList
# And another method using the operator module...
#~ import operator
#~ numList.sort(key=operator.itemgetter(1))
#~ print 'Numerical List: ', numList
</code>
HTH,
Bill
More information about the Tutor
mailing list