[英]Python way to detect if list of list of from-to values contains sequential numbers to the max
我有一个id字典作为键,还有一个列表列表,该列表包含给定id的from和to整数值。 所以看起来像这样:
{1: [[0,100], [100, 500], [500, 800]], 2: [[0, 700], [800, 1000]]}
我正在尝试建立一种检查方法,以确保每个id的数字序列提供连续的数字列表,且不带跳过。 因此,在上面的示例中,id 2将被标记,因为它的范围是700到800,而不是700到700。我不确定实现此目的的最佳方法是什么。 任何建议将不胜感激。
希望这可以帮助:
from itertools import chain
for key,value in a.iteritems():
lst=list(chain(*sorted(value)))
if len([i for i in lst if lst.count(i)==1])==2:
print "okay with key %s"%key
else:
print "Flagged with key %s"%key
为您输入:
{1: [[0,100], [100, 500], [500, 800]], 2: [[0, 700], [800, 1000]]}
输出将是:
okay with key 1
Flagged with key 2
这个怎么样:
使用itertool的成对配方:
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
data = {1: [[0,100], [100, 500], [500, 800]], 2: [[0, 700], [800, 1000]]}
for k,v in data.items():
for a,b in pairwise(v):
if a[-1]!=b[0]:
print("key",k,"fail elemen",a,"and elemn",b,"in value",v)
输出
key 2 fail elemen [0, 700] and elemn [800, 1000] in value [[0, 700], [800, 1000]]
我最终想出了一个不同的解决方案。 见下文:
d = {1: [[0,100], [100, 500], [500, 800]], 2: [[0, 700], [800, 1000]]}
for a in d.keys():
x = [[i,i+1] for i,v in enumerate(d[a][:-1]) if v[1] != d[a][i+1][0]]
if len(x) > 0:
print a
所以然后打印2。
无论如何,谢谢您的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.