4

我有两个维度数据存储在一个排序的元组列表中,如下所示:

data = [(0.1,100), (0.13,300), (0.2,10)...

每个元组中的第一个值,即 X 值,仅在元组列表中出现一次。换句话说,0.1 等只能有一个值。

然后我有一个排序的桶列表。桶定义为包含范围和 id 的元组,如下所示:

buckets = [((0,0.14), 2), ((0.135,0.19), 1), ((0.19,0.21), 2), ((0.19,0.24), 3)...

范围是相对于 X 轴的。所以,id 2 上面有两个桶,id 1 和 3 分别只有一个。id 2 的第一个桶的范围是 0 到 0.14。请注意,存储桶可以重叠。

所以,我需要一种算法,将数据放入桶中,然后将分数相加。对于上面的数据,结果将是:

1:0
2:410
3:10

注意每条数据是如何被与 id 2 关联的存储桶捕获的,因此它得到 score 100+300+10=410

我该如何编写算法来做到这一点?

4

3 回答 3

1

将每个桶定义(标签范围)转换为可调用的 - 给定数据元组 - 将增加桶总数。桶值存储在一个简单的字典中。如果您想提供更简单的 api,您可以轻松地将这个概念封装在一个类中。

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)
于 2012-12-02T01:13:39.343 回答
1

这会从您的测试数据中产生所需的输出:

data = [(0.1,100), (0.13,300), (0.2,10)]
buckets = [((0,0.14), 2), ((0.135,0.19), 1), ((0.19,0.21), 2), ((0.19,0.24), 3)]

totals = dict()

for bucket in buckets:
    bucket_id = bucket[1]
    if bucket_id not in totals:
        totals[bucket_id] = 0
    for data_point in data:
        if data_point[0] >= bucket[0][0] and data_point[0] <= bucket[0][1]:
            totals[bucket_id] += data_point[1]

for key in sorted(totals):
    print("{}: {}".format(key, totals[key]))
于 2012-12-02T01:27:29.060 回答
1

试试这个代码:

data = [(0.1,100), (0.13,300), (0.2,10)]
buckets = [((0,0.14), 2), ((0.135,0.19), 1), ((0.19,0.21), 2), ((0.19,0.24), 3)]

def foo(tpl): ## determine the buckets a data-tuple is enclosed by list of IDs
    x, s = tpl
    lst = []
    for bucket in buckets:
        rnge, iid = bucket
        if x>rnge[0] and x<rnge[1]: lst.append(iid)
    return lst

data = [[dt, foo(dt)] for dt in data]

scores_dict = {}
for tpl in data:
    score = tpl[0][1]
    for iid in tpl[1]:
        if iid in scores_dict: scores_dict[iid]+=score
        else:                  scores_dict[iid] =score

for key in scores_dict:
    print key,":",scores_dict[key]

此代码段导致:

2 : 410
3 : 10

如果未打印任何存储桶 ID,则该存储桶中没有 X 值或总和为零。

于 2012-12-02T00:52:15.297 回答