如何遍历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 发布于 2015-06-04 23:31:46
您可以将列表切片用作:
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]发布于 2015-06-04 23:32:55
看来你在找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)]https://stackoverflow.com/questions/30655902
复制相似问题