假设我有一个包含5个元素x=[a,b,c,d,e]
的列表,我想运行一个for循环,打印所有列表,其中两个条目比原始列表中的相应条目少1个。
在Python中执行此操作的简单方法是什么?提前谢谢。
编辑:如果我想要x=[4,5,6,7,8]
:
[3,4,6,7,8], [3,5,5,7,8], [3,5,6,6,8] etc.
答案 0 :(得分:2)
这样的事情:
>>> from itertools import combinations
>>> lis = [0,1,2,3,4]
>>> for x,y in combinations(range(len(lis)),2):
l = lis[:]
l[x] -= 1
l[y] -= 1
print l
...
[-1, 0, 2, 3, 4]
[-1, 1, 1, 3, 4]
[-1, 1, 2, 2, 4]
[-1, 1, 2, 3, 3]
[0, 0, 1, 3, 4]
[0, 0, 2, 2, 4]
[0, 0, 2, 3, 3]
[0, 1, 1, 2, 4]
[0, 1, 1, 3, 3]
[0, 1, 2, 2, 3]
更短的版本:
for x,y in combinations(range(len(lis)),2):
print [item - 1 if i in (x,y) else item for i,item in enumerate(lis)]
...
[-1, 0, 2, 3, 4]
[-1, 1, 1, 3, 4]
[-1, 1, 2, 2, 4]
[-1, 1, 2, 3, 3]
[0, 0, 1, 3, 4]
[0, 0, 2, 2, 4]
[0, 0, 2, 3, 3]
[0, 1, 1, 2, 4]
[0, 1, 1, 3, 3]
[0, 1, 2, 2, 3]
答案 1 :(得分:2)
from itertools import combinations
a = [1,2,3,4]
for combination in combinations(range(len(a)),r=2):
print [c-(1 if i in combination else 0) for i,c in enumerate(a)]