我的子程序生成如下列表。
x_list=[292, 314, 451, 454, 460, 464, 468, 476, 1231, 1441, 1445]
基本上,我必须计算每个元素之间的差异,如果差异> 10,我必须保留只有前一个元素不同的大元素。
之间的区别451 & 454 = 3
454 & 460 = 6
460 & 464 = 4
464 & 468 = 4
468 & 476 = 8
Total = 25 (3+6+4+4+8)
由于每个元素之间的差异小于10,我必须在字典中仅保留值47的476。
我想要的输出是:
x_dict={292: 0, 314: 0, 476: 25, 1231: 0, 1445: 4}
以下是我的计划:
for elem in range(1,len(x_dict)):
ii = 10
print elem
diff=x_dict[elem]-x_dict[elem-1]
print diff
if diff <= 10:
if x_dict[elem] not in x_dict:
new_index = x_dict[elem]
ii = ii + diff
print "ii : ", ii
print "Index :", new_index
x_dict.update({new_index: ii})
else:
value=x_dict.get(elem, None)
value=value+diff
print "Value is : ", value
print "Index is : ", new_index
x_dict[elem] = value
else:
if x_dict[elem-1] not in x_dict:
new_index = x_dict[elem - 1]
print "Out ", new_index
x_dict.update({new_index: ii})
答案 0 :(得分:1)
我使用偏移拉链技巧,然后将循环视为状态机
状态是2个布尔(b-a) ? 10
和f
'标志'中的2位,表示(b-a) <= 10
的“运行”
启动在初始化o = [(x_list[0], 0)]
中启动
并且针对列表在(b-a) <= 10
在循环中操作列表而不是尝试动态构建字典似乎很自然
将元组列表转换为最后的字典
x_list=[292, 314, 451, 454, 460, 464, 468, 476, 1231, 1441, 1445]
o, f, sm = [(x_list[0], 0)], 0, 0
for (a, b) in zip(x_list, x_list[1:]):
if (b-a) > 10 and f == 0:
o.append((b, 0))
sm = 0
if (b-a) <= 10 and f == 0:
f = 1
o.pop()
if (b-a) <= 10 and f == 1:
sm += b-a
if (b-a) > 10 and f == 1:
o.append((a, sm))
f, sm = 0, 0
o.append((b, 0))
if (b-a) <= 10 and f == 1:
o.append((b, sm))
dict(o)
Out[268]: {292: 0, 314: 0, 476: 25, 1231: 0, 1445: 4}