2013-04-04 58 views
0

我有如下列表中的值列表中的一个条目:如何删除基于子表

list = [ [1,2,3,4,5], 
     [1,2,3,3,5], 
     [1,2,3,2,5], 
     [1,2,3,4,6] ] 

我想通过这个列表来解析和删除的条目,如果满足以下条件:

  1. 如果list[i][0]相同list[i+1][0]
  2. 如果list[i][4]相同list[i+1][4]

这将导致以下列表:

list = [ [1,2,3,4,5], 
     [1,2,3,4,6]] 

任何帮助深表感谢。谢谢。

编辑:使用Python 2.5.4

+2

只是一句话:从你的描述我会删除条目0和1(因为你的条件索引)。 – Howard 2013-04-04 08:46:55

+0

@Howard你是对的。它可能是删除条目0和1。取决于解决方案的实施方式。无论如何,两者都可以。 – 2013-04-04 08:59:11

回答

3

使用列表理解保留一切不符合条件:

[sublist for i, sublist in enumerate(yourlist) 
    if i + 1 == len(yourlist) or (sublist[0], sublist[4]) != (yourlist[i+1][0], yourlist[i + 1][4])] 

所以,任何行要么是最后一个,或者其中第一并且最后一个元素与下一行中的相同列不匹配是允许的。

结果:

>>> [sublist for i, sublist in enumerate(yourlist) 
...  if i + 1 == len(yourlist) or (sublist[0], sublist[4]) != (yourlist[i+1][0], yourlist[i + 1][4])] 
[[1, 2, 3, 2, 5], [1, 2, 3, 4, 6]] 
+0

这就像一个魅力。谢谢。 – 2013-04-05 01:14:41

0

不够简明非列表解析版本。

list = [ [1,2,3,4,5], 
     [1,2,3,3,5], 
     [1,2,3,2,5], 
     [1,2,3,4,6] ] 

output = [] 

for i, v in enumerate(list): 
    if i +1 < len(list): 
     if not (list[i][0] == list[i+1][0] and list[i][4] == list[i+1][4]): 
      output.append(v) 
    else: 
     output.append(v) 

print output 
+0

我喜欢如何做到这一点。容易明白。谢谢。 – 2013-04-05 01:15:57

0

只是将一些itertools桌子上:-)

from itertools import izip_longest 

l = [ [1,2,3,4,5], 
     [1,2,3,3,5], 
     [1,2,3,2,5], 
     [1,2,3,4,6] ] 

def foo(items): 
    for c, n in izip_longest(items, items[1:]): 
     if not n or c[0] != n[0] or c[4] != n[4]: 
      yield c 

print list(foo(l)) 

输出:

[[1, 2, 3, 2, 5], [1, 2, 3, 4, 6]] 

如果你不介意的话,这不工作不到位放而创建一个新的list

编辑:

既然你说你正在使用2.5.4我们,你可以使用的方法类似下面,而不是izip_longest

# warning! items must not be empty :-) 
def zip_longest(items): 
    g = iter(items) 
    next(g) 
    for item in items: 
     yield item, next(g, None) 
+0

我不介意创建一个新的列表。但我目前使用2.6,所以没有izip_longest。 – 2013-04-04 09:04:50

+0

[izip_longest(http://docs.python.org/2/library/itertools.html#itertools.izip_longest)是缴费在2.6 – sloth 2013-04-04 09:05:49

+0

对不起我的坏,我使用2.5。4:| ImportError:无法导入名称izip_longest – 2013-04-04 09:31:47

0

我觉得列表理解是最适合这种码。

res = [value for index, value in enumerate(a) if not (index < len(a)-1 and value[0]==a[index+1][0] and value[4]==a[index+1][4])] 
+0

谢谢。将更多地研究列表理解。 :) – 2013-04-05 01:15:12