簡體   English   中英

從列表列表中刪除第一個元素,然后是第一個和第二個元素[保留]

[英]Removing the 1st element then 1st and 2nd element from a list of lists [on hold]

我的目標是刪除列表的第一個元素,然后刪除列表的第一個和第二個元素等。所以輸入的列表如下: [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]將返回如下列表: [[1,2],[1,3],[2,3]我嘗試了很多東西,但沒有一個效果很好

像這樣的東西怎么樣:

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)
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)}" )

根據您的描述,我認為f 是您正在尋找的 function 。 這是上面腳本的output:

[[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]]

. 請注意,輸入未就地修改; 如果需要,您需要稍微調整代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM