how to sorted by summed itemgetter(x)

A

Aldarion

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?
 
P

Paul Rubin

Aldarion said:
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)))
 
A

Aldarion

Thanks for the reply,I got it.
Aldarion said:
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)))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,113
Latest member
Vinay KumarNevatia
Top