簡體   English   中英

Python:如果滿足條件,則將列表項添加到字典中

[英]Python: Adding list items to a dictionary if conditions are met

我試圖將數字之間的差異相加,直到總差異> 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]
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]

一方面,您在使用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_list的范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM