2012-08-01 118 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

相關問題