萧十郎
>>> a = [1,2,3,2,4,2,5]>>> a[:] = [10 if x==2 else x for x in a]>>> a[1, 10, 3, 10, 4, 10, 5]如果要替换多个项目,请考虑使用dict:>>> dic = {2 : 10}>>> a[:] = [dic.get(x,x) for x in a]>>> a[1, 10, 3, 10, 4, 10, 5]
达令说
您正在寻找enumerate():for indx, ele in enumerate(a): if ele == 2: a[indx] = 10print a印刷:[1, 10, 3, 10, 4, 10, 5]如果要更改的值是输入,则只需执行以下操作:change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())for indx, _ in enumerate(a): if change[0] == 2: a[indx] = change[1]或作为列表理解(如果您喜欢此解决方案,请支持Ashwini的:)):change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())[change[1] if x == change[0] else x for x in a]