如何跳过python列表中的当前元素

时间:2015-06-04 23:29:44

标签: python

如何循环遍历python列表,将每个项目添加到除当前项目之外的另一个列表中:

list = [1,2,8,20,11]

for i,j in enumerate(list):
    print j[i+1:]
#this will only give [2,8,20,11] then [8,20,11],[20,11], [11]

#but I want something like [2,8,20,11], [1,8,20,11],[1,2,20,11]... etc.
#then 1,8,20,11
#then 

2 个答案:

答案 0 :(得分:3)

看起来你在combinations之后,例如:

>>> from itertools import combinations
>>> data = [1,2,8,20,11]
>>> list(combinations(data, 4))
[(1, 2, 8, 20), (1, 2, 8, 11), (1, 2, 20, 11), (1, 8, 20, 11), (2, 8, 20, 11)]

答案 1 :(得分:2)

您可以使用list slicing作为:

lst = [1,2,8,20,11]
for i in xrange(len(lst)):
    print lst[:i]+lst[i+1:]

>>> [2, 8, 20, 11]
    [1, 8, 20, 11]
    [1, 2, 20, 11]
    [1, 2, 8, 11]
    [1, 2, 8, 20]