By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,247 Members | 1,165 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,247 IT Pros & Developers. It's quick & easy.

how to sorted by summed itemgetter(x)

P: n/a
for example, let
from operator import itemgetter
items = [('a', [5, 2]), ('c', [1]), ('b', [6]), ('d', [7])]
sorted(items, key = itemgetter(1))
get this back:
[('c', [1]), ('a', [5, 2]), ('b', [6]), ('d', [7])]

but
sorted(items, key = sum(itemgetter(1)))
raise a errer:
'operator.itemgetter' object is not iterable

how to sorted by summed itemgetter(1)?
maybe sorted(items,key = lambda x:sum(x[1]))
can't itemgetter be used here?

Jun 25 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Aldarion <Er*************@gmail.comwrites:
how to sorted by summed itemgetter(1)?
maybe sorted(items,key = lambda x:sum(x[1]))
can't itemgetter be used here?
You really want function composition, e.g.

sorted(items, key=sum*itemgetter(1))

where * is a composition operator (doesn't exist in Python).

You could write:

def compose(f,g):
return lambda *a,**k: f(g(*a,**k))

and then use

sorted(items, key=compose(sum,itemgetter(1)))

or spell it out inline:

sorted(items, key=lambda x: sum(itemgetter(1)(x)))

I'd probably do something like:

snd = itemgetter(1) # I use this all the time
sorted(items, key=lambda x: sum(snd(x)))
Jun 25 '07 #2

P: n/a
Thanks for the reply,I got it.
On 6 25 , 9 19 , Paul Rubin <http://phr...@NOSPAM.invalidwrote:
Aldarion <ErendisAldar...@gmail.comwrites:
how to sorted by summed itemgetter(1)?
maybe sorted(items,key = lambda x:sum(x[1]))
can't itemgetter be used here?

You really want function composition, e.g.

sorted(items, key=sum*itemgetter(1))

where * is a composition operator (doesn't exist in Python).

You could write:

def compose(f,g):
return lambda *a,**k: f(g(*a,**k))

and then use

sorted(items, key=compose(sum,itemgetter(1)))

or spell it out inline:

sorted(items, key=lambda x: sum(itemgetter(1)(x)))

I'd probably do something like:

snd = itemgetter(1) # I use this all the time
sorted(items, key=lambda x: sum(snd(x)))

Jun 25 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.