我在一个叫做事件的对象上循环。每个事件中都有一个特定的对象。我在计算具有特定特征的物体的比例。将这种方法想象成如下所示:
for event in events:
countCars =+ 1
if event.car.isBlue() is True:
countCarsBlue =+ 1
print("fraction of cars that are blue: {fraction}".format(
fraction = countCarsBlue / countCars))
现在,假设我想计算在另一个物体的特征区域中具有特定特征的物体的比例。所以,在我的例子中,我计算的是蓝色汽车的比例。现在,我想计算在汽车长度从0米到1米范围内蓝色汽车的比例,在汽车长度从1米到2米,从2米到3米,从3米到4米范围内蓝色汽车的比例,依此类推。你知道吗
考虑到我要处理大量的统计数据和比我的简单示例中的4个存储箱多得多的存储箱,假设存储箱宽度不变,那么构造这种类型计算的代码的好方法是什么?你知道吗
(对于可变料仓宽度,是否有合理的方法来实现这一点?)你知道吗
如果您使用的是python3.4+,枚举实际上对此非常有用。下面是几个你可以做的例子:
如果你说的是连续范围,
lower < value < upper
是一个很好的检查方法。若您有离散值(如颜色),您可以创建一个有趣的颜色集合,并检查该集合中的成员资格。还要注意的是,您可以很容易地使用可变的箱子大小。你知道吗如果您对简单的计数感兴趣,还可以使用^{} 。请注意,如果您的项目是引用对象,则更改一个集合中的某个项目将更改另一个集合中的某个项目:
首先,编写一些代码来重新创建示例:
好的,现在我随机创建十个
car
对象并将它们添加到event
:对我来说,输出如下(您的输出当然可以不同):
现在,如果我们想按地区统计我们的事件,您可以按以下步骤进行:
对于上述示例数据,将打印:
相关问题 更多 >
编程相关推荐