Mahmoud Ayman
Mahmoud Ayman

Reputation: 197

I want to sort a list in a method with respect to the method's argument

I have a method and as an argument I enter x and y coordinates of a point and then I calculate the power reached to that [x,y] coordinate from other points and sort them in order of highest power reached to lowest:

def power_at_each_point(x_cord, y_cord):
    nodez_list = [nodes_in_room for nodes_in_room in range(1, len(Node_Positions_Ascending) + 1)]
    powers_list = []
    for each_node in nodez_list:
    powers_list.append(cal_pow_rec_plandwall(each_node, [x_cord, y_cord]))
    return max(powers_list)

I want to do that in a more pythonic way like key = cal_pow_rec_plandwall but this method takes two arguments and not one. So how can I do it?

Upvotes: 1

Views: 49

Answers (1)

chepner
chepner

Reputation: 531748

You just need a single call to max which takes a generator as an argument. The lambda expression is just to make things more readable.

def power_at_each_point(x_cord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])      
    return max(f(each_node) for each_node in xrange(1, len(Node_Positions_Ascending) + 1))

You can replace the generator with a call to itertools.imap:

from itertools import imap

def power_at_each_point(x_coord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])
    return max(imap(f, xrange(1, len(Node_Positions_Ascending) + 1)))

Upvotes: 1

Related Questions