示例:
a = [1,2,3,2,4,2,5]
for key in a:
if key == 2:
key = 10
print key
结果:[1,10,3,10,4,10,5]
我需要Python手动“询问”要替换哪些元素。
答案 0 :(得分:7)
>>> 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]
答案 1 :(得分:4)
您正在寻找enumerate()
:
for indx, ele in enumerate(a):
if ele == 2:
a[indx] = 10
print 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]
或者作为列表理解(如果你喜欢这个解决方案upvote 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]