TypeError: <lambda>() missing 1 required positional argument: 'item'

Viewed 2148

I cant seem to figure out what the problem is here.i'm using this code to create multiple groups of numbers from an array.i'm not sure if it is a python compatibility issue or not.


data=[]
data=1,2,3,4,6,7,8,11,12
for k, g in groupby(enumerate(data), lambda i, x: i-x):
    print map(itemgetter(1), g)

<TypeError: <lambda>() missing 1 required positional argument: 'x'

2 Answers

Assuming this is Python 2.x - you're just missing a pair of brackets around the lambda's parameters:

for k, g in groupby(enumerate(data), lambda (i, x): i-x):
    print map(itemgetter(1), g)

You here defined with lambda i, x : i - x a function that takes two parameters, but the groupby function only takes one parameter. In this case a 2-tuple.

You thus can obtain the elements with subscripting:

for k, g in groupby(enumerate(data), lambda x: x[0]-x[1]):
    print(map(itemgetter(1), g))

or in , you can use iterable unpacking:

for k, g in groupby(enumerate(data), lambda (i, x): i - x):
    print(map(itemgetter(1), g))

here we thus unpack the tuple in two parameters i and x.

Related