一个班轮。使用来自列表中 class 个实例的方法绘制直方图
One liner. Plotting a histogram using a method from class instances in a list
我刚学会使用pythonic lambda。
为什么这样有效:
print(max(my_firms, key=lambda firm: firm.num_members()))
但这不会:
plt.hist(my_firms, key=lambda firm: firm.num_members())
也就是。我有一个列表 my_firms,其中包含 class 个实例,公司,具有方法 num.members()。我想用 my_firms.
中所有公司的成员数量做一个直方图
非常感谢
并非每个方法都接受 key
参数。事实上,大多数 不会。我怀疑 matplotlib 的 hist
函数没有。
在这种情况下,您可能希望使用 list comprehension 将 firm
对象转换为成员数:
plt.hist([f.num_members() for f in my_firms])
在其他地方,您可能会使用 generator expression,但是 IIRC,plt.hist
需要一个类似数组的对象,而生成器不太符合要求。
据我所知,plt.hist
不接受任何名为 key
的关键字参数。检查文档。
至于你的情节,你可能会通过这样的列表理解来实现你正在寻找的东西:
plt.hist([f.num_members() for f in my_firms])
我刚学会使用pythonic lambda。 为什么这样有效:
print(max(my_firms, key=lambda firm: firm.num_members()))
但这不会:
plt.hist(my_firms, key=lambda firm: firm.num_members())
也就是。我有一个列表 my_firms,其中包含 class 个实例,公司,具有方法 num.members()。我想用 my_firms.
中所有公司的成员数量做一个直方图非常感谢
并非每个方法都接受 key
参数。事实上,大多数 不会。我怀疑 matplotlib 的 hist
函数没有。
在这种情况下,您可能希望使用 list comprehension 将 firm
对象转换为成员数:
plt.hist([f.num_members() for f in my_firms])
在其他地方,您可能会使用 generator expression,但是 IIRC,plt.hist
需要一个类似数组的对象,而生成器不太符合要求。
据我所知,plt.hist
不接受任何名为 key
的关键字参数。检查文档。
至于你的情节,你可能会通过这样的列表理解来实现你正在寻找的东西:
plt.hist([f.num_members() for f in my_firms])