0
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 中丢失怎么办。这里也应该报错

4

3 回答 3

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)]
于 2012-08-01T20:13:07.070 回答
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
于 2012-08-01T20:11:40.737 回答
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)]
于 2012-08-01T21:13:03.943 回答