2012-08-01 117 views
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中失踪,也会如何。应该在这里被报道一个错误以及

+0

这与您以前的问题有何不同? (http://stackoverflow.com/questions/11763448/how-to-report-an-error-if-an-element-is-missing-in-the-list-of-lists) – mgilson 2012-08-01 20:09:01

+0

它和我一样我坚持在这一个。 – smazon09 2012-08-01 20:10:50

+0

它通常是**真的**皱起眉头发表同样的问题两次。 – mgilson 2012-08-01 20:17:36

回答

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)] 
+0

输出不显示(2,4)在列表中错过了(3,2) – smazon09 2012-08-01 21:20:55

+0

对不起(3,2)罚款但是(2,4)缺失输出 – smazon09 2012-08-01 21:22:14

+0

也如果(1,1)或(2,1)缺失? – smazon09 2012-08-02 01:11:00

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 
+0

是的,它是列表清单 – smazon09 2012-08-01 20:13:31

+0

@ smazon09:见编辑 – 2012-08-01 20:21:47

+0

我已完成编辑部分。无论如何感谢 – smazon09 2012-08-01 20:28:56

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)] 
+0

如果我必须检测到第一次出现错误,那么当我纠正它时应该检测到下一个错误等等。我希望你明白我的观点 – smazon09 2012-08-01 20:30:20

相关问题