[英]Removing the 1st element then 1st and 2nd element from a list of lists [on hold]
My aim is to remove the 1st element of a list and then the first and second element of a list etc. So a list entered like this: [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
will return a list like this: [[1,2],[1,3],[2,3]
I have tried many things but none work well我的目标是删除列表的第一个元素,然后删除列表的第一个和第二个元素等。所以输入的列表如下:
[[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]]
将返回如下列表: [[1,2],[1,3],[2,3]
我尝试了很多东西,但没有一个效果很好
How about something like this:像这样的东西怎么样:
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)
And as @schwobaseggl commented, this code could be what you are looking for:正如@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)}" )
I think f is a function you are looking for based on your description.根据您的描述,我认为f 是您正在寻找的 function 。 Here is the output of the above script:
这是上面脚本的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]]
. . Note that the input is NOT modified in place;
请注意,输入未就地修改; you'd need to adapt the code a little if you want that.
如果需要,您需要稍微调整代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.