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)]
开头,用于检测列表中的缺失,因此它遵循序列中的每个项目
答案 0 :(得分: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
答案 1 :(得分: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}}