开发者

Create copy of list and remove element

I would like to write something like this

S = [ 0, 1, 2 ]
F =开发者_JAVA技巧 [ S.without(i) for i in range(0,len(S)) ]
print F

and Python putting out

[ [0,1], [0,2] ,[1,2] ]

and have not found something like this in the online reference. Can you help me?


Python provides itertools.combinations, which does exactly what you want:

>>> import itertools
>>> s = [0,1,2]
>>> list(itertools.combinations(s, len(s) - 1))
[(0, 1), (0, 2), (1, 2)]

Even better, it returns a generator, so you can easily iterate over all combinations without using much memory.


>>> S = [0, 1, 2]
>>> F = [S[0:i] + S[i+1:] for i in range(len(S))]
>>> print F
[[1, 2], [0, 2], [0, 1]]
>>> 

If you don't need the elements to be in any order -- that is, if you can use sets -- and if you want to remove items by value rather than by index, then this is a more elegant solution:

>>> S = set(range(3))
>>> F = [S - set((i,)) for i in S]
>>> F
[set([1, 2]), set([0, 2]), set([0, 1])]


A nested list comprehension can do the job:

>>> S = [ 0, 1, 2 ]
>>> F = [[x for x in S if x != s] for s in S]
>>> print F
[[1, 2], [0, 2], [0, 1]]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜