从列表列表中删除第一个元素,然后删除第一个和第二个元素

时间:2019-10-20 09:37:15

标签: python python-3.x list

我的目标是删除列表的第一个元素,然后删除列表的第一个和第二个元素,以此类推。因此,这样输入的列表:[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]将返回如下的列表:[[1,2],[1,3],[2,3] 我已经尝试了很多东西,但是都无法正常工作

2 个答案:

答案 0 :(得分:0)

这样的事情怎么样:

list1 = [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
list2 = []

keep_index = 1
increment = 0
for i in range(len(list1)):
    if i == keep_index:
        list2.append(list1[i])
        increment += 2 if keep_index == 2 else 1
        keep_index += increment
print(list2)

正如@schwobaseggl所评论的那样,这段代码可能就是您想要的:

import itertools
itertools.combinations([1, 2, 3], 2) # combinations of 2 elements (without repeats)

答案 1 :(得分:0)

import itertools

def f( l ): 
    def elements_to_remove():
        for i in itertools.count( 1 ): 
            yield from itertools.repeat( i, i )

    def _g():
        es = elements_to_remove()

        skip = None
        e = next( es )

        while True:
            skip = (yield not skip)[0] == e
            e    = next( es ) if skip else e

    g = _g()
    next( g )
    return list( filter( g.send, l ) )

inputs = [] 
inputs.append( [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] )
inputs.append( [[0,0],[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] )
inputs.append( [[2,0],[1,0]] )

for input in inputs:
    print( f"{input} -> {f(input)}" )

I think f是您正在根据描述查找的功能。这是上面脚本的输出:

[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]] -> [[1, 2], [1, 3], [2, 3]]
[[0, 0], [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]] -> [[0, 0], [1, 2], [1, 3], [2, 3]]
[[2, 0], [1, 0]] -> [[2, 0]]

。请注意,输入未在适当位置修改;如果需要,您需要稍微修改一下代码。