Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
for循环中的Python更改列表元素_Python_List - Fatal编程技术网

for循环中的Python更改列表元素

for循环中的Python更改列表元素,python,list,Python,List,假设我有一个包含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. 大概是这样的: >>> from itertools import combinations >>> lis = [0,1,2,3,4] &

假设我有一个包含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.
大概是这样的:

>>> 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]

所以你会想要
[a-1,b-1,c,d,e]
[a-1,b,c-1,d,e]
[a-1,b,c,d-1,e]
等等。这个问题没有任何意义,原始列表是什么?列表是否包含ascii字符或数字或什么?请发布输入和预期输出。@F.J是的,就是这样。@F.J-你的心灵能力给我留下了深刻的印象!
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)]