Python:在条件为m时向字典中添加列表项

2024-10-02 02:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

输出应该是多个字典条目,它们的列表差异加起来是最接近的数字<;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

输出应该是

^{pr2}$

Tags: innumber列表for字典数字差异num
2条回答

首先,在将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

正如ndpu指出的,你的最后一个x将超出你的num_列表的范围。在

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

输出:

^{pr2}$

相关问题 更多 >

    热门问题