Python:如果满足条件,则将列表项添加到字典中

时间:2014-02-26 18:21:24

标签: python list loops dictionary

我正在尝试添加数字之间的差异,直到总差异> 20,将数字附加到一个列表,该列表成为字典值,其中键是number_set。我现在收到一个超出范围错误的列表。

输出应该是多个字典条目,其列表差异加起来最接近的数字< 20。

number_set = 1
number_dict = {}

num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

incl_num_list = []
total = 0

for x in range(1, len(num_list)):

    if total < 20:
        total = total + (num_list[x+1] - num_list[x])
        incl_num_list.append(num_list[x])
    else:
        number_dict.update({km: num_list})
        km += 1
        incl_num_list = []
        total = 0

for k, v in number_dict.items():
    print k
    print v

输出应为

1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

2 个答案:

答案 0 :(得分:2)

num_list = [1, 3, 5, 9, 18, 20, 22, 25, 27, 31]

overflow = 20
total = 0
key = 1
number_dict = {1: [1]}

for left, right in zip(num_list[:-1], num_list[1:]):
    total += right - left
    if total >= overflow:
        key += 1
        number_dict[key] = [right]
        total = 0
    else:
        number_dict[key].append(right)

for k, v in sorted(number_dict.items()):
    print k
    print v

输出:

1
[1, 3, 5, 9, 18, 20]
2
[22, 25, 27, 31]

答案 1 :(得分:1)

首先,您在将km分配给任何内容之前使用Traceback (most recent call last): File "<pyshell#29>", line 15, in <module> number_dict.update({km: num_list}) NameError: name 'km' is not defined

{{1}}

正如ndpu指出的那样,你的最后一个x将超出你的num_list范围。