0

I have just learned to use pythonic lambda. Why this works:

print(max(my_firms, key=lambda firm: firm.num_members()))

But this will not:

plt.hist(my_firms, key=lambda firm: firm.num_members())

That is. I have a list, my_firms, that contains class instances, firm, that have a method num.members(). I want to do a histogram with the quantity of members of all firms in my_firms.

Thanks a lot

B Furtado
  • 1,488
  • 3
  • 20
  • 34

2 Answers2

3

Not every method will accept a key argument. In fact, most don't. I suspect that matplotlib's hist function is one that doesn't.

In this case, you'll probably want to use a list comprehension to transform the firm objects into numbers of members:

plt.hist([f.num_members() for f in my_firms])

In other places, you'll probably use a generator expression instead, but IIRC, plt.hist expects an array-like object and generators don't quite fit the bill.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

As far as I know, plt.hist doesn't take any keyword arguments called key. Check the documentation.

As for your plot, you can are probably achieve what you are looking for with a list comprehension like this:

plt.hist([f.num_members() for f in my_firms])
Gustavo Bezerra
  • 9,984
  • 4
  • 40
  • 48