-1

I want to create a list of tuples with first element from a list, and the second element from a function of the element of list, then find the minimum from the output of the function. The code below best explains what I want:

x,y = min((x,f(x) for x in array), key = lambda(k, v): v[1])

After running the script, I am getting:

SyntaxError: invalid syntax

NOTE: f(x) returns int/float


Update: I wrote my code from another stack overflow question, so I didnt know what exactly I was doing. Can someone explains how key works?
Thanks for the answers :)
SeeknInspYre
  • 360
  • 1
  • 3
  • 16

4 Answers4

2

You need to add some parenthesis:

x, y = min(((x,f(x)) for x in array), key = lambda t: t[1][1])

I adjusted the lambda expression to work in both Python 2 and 3 (where you cannot use tuple unpacking in the parameter list).

Remember that the key is just a function that is supposed to return the value for which we want to know the minimum. It is called for each element in the input sequence. In this case that's a (x, f(x)) tuple, and you wanted to find the minimum by the second element of the f(x) return value.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

In your list comprehension, the , is not parsed as a tuple expression. You need to wrap it with () to make the parser know.

x,y = min(( (x,f(x)) for x in array), key = lambda(k, v): v[1])
shx2
  • 61,779
  • 13
  • 130
  • 153
1

I guess you want this:

x,y = min(((x,f(x)) for x in array), key = lambda(k, v): v)
Johannes Charra
  • 29,455
  • 6
  • 42
  • 51
1

Either add the missing parentheses, or rewrite the code like so:

y, x = min(zip(map(f, array), array))

I've swapped the order of the tuple elements to not have to supply a key function to min().

Here is another version:

x = min(array, key=f)
y = f(x)

It's short and clear, but makes an additional call to f().

NPE
  • 486,780
  • 108
  • 951
  • 1,012