如果列表中的项目按顺序丢失,如何报告错误

时间:2012-08-01 20:07:26

标签: python

for i, e in enumerate(l1):
    if (e[0] == e[1]) and ((e[0], e[1]) not in l1):
        raise ValueError, '%s is missing' %(e[0], e[1])

    if i!=len(l1)-1:
        if e[0]==l1[i+1][0] and e[1]!=l1[i+1][1]-1:
            raise ValueError, '(%s,%s) is missing ' %(e[0], e[1]+1)

l1 = [(1,2),(1,3),(1,4),(2,1),(2,3)]

我可以为缺失(1,2)和(2,2)工作但是在上面的情况下首先它应该寻找(1,1)报告错误,如果它不存在但是在上面的代码中它未被发现。同样,它应该遍历整个列表以检查是否有任何遗漏。如果我想要(2,4)并且在l1中丢失它也会怎样。这里也应该报告错误

3 个答案:

答案 0 :(得分:1)

一般而言:

from itertools import product

#`m` and `n` denote the upper limit to the domain of the first and second tuple elements.
complete_set = set(product(range(1, n), range(1, m)))

#`i` is whichever sublist you want to test. You get the idea.
test_set = set(l1[i])

missing_set = complete_set - test_set

修改

检查序列是否出现故障:

sorted(sequence) == sequence

答案 1 :(得分:1)

l1=[(1, 1), (1, 2), (1, 4), (2, 1), (2, 2), (2, 5)]
for i,elem in enumerate(l1[:-1]):
    nxt = ((elem[0],elem[1]+1),(elem[0]+1,elem[1]))
    if l1[i+1] not in nxt:
       print "Error, something is missing should be one of:",list(nxt)

输出:

Error, something is missing should be one of: [(1, 3), (2, 2)]
Error, something is missing should be one of: [(1, 5), (2, 4)]
Error, something is missing should be one of: [(2, 3), (3, 2)]

答案 2 :(得分:0)

我忽略了你的另一个问题,因为你只需要检查前面的字母是否相同。

编辑:显然我错过了一些。新的解决方案非常低效且有点难看:

missing = []
num = {}
for i,e in enumerate(l1):
    if not e[0] in num:                # first number groups
        num[e[0]] = []                 # make a list of them (empty... for now)
        for z,q in enumerate(l1):      # for all of the numbers
            if q[0]==e[0]:             # that are in the first number group
                num[e[0]].append(q[1]) # append 
                                       # then start again with second number group

for i in num.keys():                            # for each number group
    for e in xrange(min(num[i]),max(num[i])+1): # from minimum to maximum, iterate
        if not e in num[i]:                     # if any number isn't there
            missing.append((i,e))               # make note

print missing # [(1, 3), (2, 3), (2, 4), (3, 2)]