-2
list = [['a', (1,1)], ['a', (1,2)], ['a', (1,4)], ['a', (1,5)]]

for i in list:
    print "the i is ", i
    print i[0]   # 'a'
    print i[1]   # (1, 1)
    n = 'a'
    v = (1,1)
    #n = re.search(r'[a-z]', i[0])
    #v = (v[0], (v[1] + 1))
    print "just", i[1]
    print "trying ", v
    for j in i:  
        if (j[0] != n):
            v = (1, 1)
            n = i[0]
        if (i[1] != v):
            print v
            raise ValueError, '[%s, %s] is missing' %(i[0], (i[1][0], i[1][1]-1))

        v = (v[0], (v[1] + 1))

在第一次迭代之后,该值似乎没有改变,即它保持为(1,1),但是我可以看到需要做什么才能报告列表中的缺失项,即在此示例列表中它是['a', (1, 3)]。通常,代码以['a', (1,1)]检测其在列表中的缺失开始,因此它按顺序跟随每个项目

4

2 回答 2

0

我见过这个反复问所以这里是一个完整的例子

def ListToDict(l):
    d = {}
    for itm in l:
        if  itm[0] not in d:d[itm[0]]=[]
        d[itm[0]].append(itm[1])
    for key in d:
        itm = d[key]
        if isinstance(itm,(list,tuple)) and len(d[key])>0 and isinstance(d[key][0],(tuple,list)):
            d[key] = ListToDict(d[key])
    return d
def ValidateSequences(d):
    if isinstance(d,(tuple,list)):
        return sorted(d) == range(min(d),max(d)+1)
    elif isinstance(d,dict):
        r = {}
        for key in d:
            r[key] = ValidateSequences(d[key])
        return r
my_list = [['a', (1,1)], ['a', (1,2)], ['a', (1,4)], ['a', (1,5)]]
d = ListToDict(my_list)
print "Validated:",ValidateSequences(d)
my_list.append(["a",(1,3)])
d = ListToDict(my_list)
print "Revalidated:",ValidateSequences(d)

输出是

Validated: {'a': {1: False}}
Revalidated: {'a': {1: True}}
于 2012-08-05T04:27:14.287 回答
0

你想放

v = (1,1)

在 for 循环之外(并且您也不想放入v = (1, 1)语句if (j[0] != n)中)。否则它将被设置回(1, 1)每次。

ETA:话虽如此,这不是解决问题的好方法。为什么不做类似的事情:

for i in range(1, 6):
    if ["a", (1, i)] not in list:
        raise ValueError, '["a", (1, %s)] is missing' % i
于 2012-08-05T03:41:29.163 回答