如何处理元组的某种模式

时间:2012-08-02 23:18:05

标签: python

如果

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

将元组的元素视为(i,j)现在我们知道如果我们知道如果(1,3)存在则那么(1,1)和(1,2)应该存在(如果有的话)它报失了错误。应首先对(1,1)然后对(1,2)进行错误检测。类似地,如果我们知道对于另一个序列,如果(2,3)存在,则类似地(2,1)和(2,2)将存在。

这也是一个示例列表。这个例子也可以是:

list_1 = [(1,3),(1,4),(2,2),(2,3),(3,1)(3,4)]现在在这种情况下如果(3,4) )然后存在(3,1),(3,2)和(3,3)。这个模式可以通过每个'i'我的代码的第j个元素的最大值来确定为gi

for i, e in enumerate(list_1):
              i1 = (1,1)
              if i1 not in list_1:
                 raise ValueError, '%s is missing in %s' %(i1, production)

              if (e[0] == e[1]) and ((e[0],e[1]) not in list_1):
                 #if i1 not in list_1:
                 raise ValueError, '%s is missing in %s' %((e[0], e[1]), production)

              print e, e[0], e[1], (e[0], e[1])
              if i!=len(list_1)-1:


                 if e[0]==list_1[i+1][0] and e[1]!=list_1[i+1][1]-1:

                    raise ValueError, '(%s,%s) is missing in %s ' %(e[0], e[1]+1, production)

2 个答案:

答案 0 :(得分:0)

>>> list_1 = [(1, 1), (1, 3), (1, 4), (2, 2), (2, 3)]
>>> check_list = zip(list_1, list_1[1:])
>>> check_list
[((1, 1), (1, 3)), ((1, 3), (1, 4)), ((1, 4), (2, 2)), ((2, 2), (2, 3))]
>>> ok = True
>>> for (i1, j1), (i2, j2) in check_list:
...     if i1 == i2 and j1 + 1 != j2:
...         ok = False
...         break
...     elif i1 + 1 != i2: #you may also want to check j2 == 1:
...         ok = False
...         break
...
>>> ok
False

答案 1 :(得分:0)

基于itertools的方法

>>> from itertools import groupby, izip, count
>>> from operator import itemgetter
>>> z = [(1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (3,1), (3,4)]
>>> z = sorted(z, key=itemgetter(0))
>>> z = groupby(z, key=itemgetter(0))
>>> bad = []
>>> for key, group in z:
...     z1 = izip((y for (x, y) in group), count(1))
...     for (a, b) in z1:
...             if a != b:
...                    bad.append(key) 
... 
>>> print(set(bad))
set([1, 3])