擅长:python、mysql、java
<p>将每个bucket定义(label range)转换为一个可调用的(给定数据元组)将增加bucket total。Bucket值存储在一个简单的dict中。如果您想提供一个更简单的api,您可以很容易地将这个概念包装在一个类中。在</p>
<pre><code>def partition(buckets, bucket_definition):
"""Build a callable that increments the appropriate buckets with a value"""
lower, upper = bucket_definition[0]
key = bucket_definition[1]
def _partition(data):
x, y = data
# Set a default value for this key
buckets.setdefault(key, 0)
if lower <= x <= upper:
buckets[key] += y
return _partition
bucket_definitions = [
((0, 0.14), 2),
((0.135, 0.19), 1),
((0.19, 0.21), 2),
((0.19, 0.24), 3)
]
data = [(0.1, 100), (0.13, 300), (0.2, 10)]
# Holder for bucket labels and values
buckets = {}
# For each bucket definition (range, label) build a callable
partitioners = [partition(buckets, definition) for definition in bucket_definitions]
# Map each callable to each data tuple provided
for partitioner in partitioners:
map(partitioner, data)
print(buckets)
</code></pre>