1

例子:

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 手动“询问”要替换哪些元素。

4

2 回答 2

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]
于 2013-06-10T04:48:27.413 回答
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]

或作为列表理解(如果您喜欢此解决方案,请支持 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]
于 2013-06-10T04:48:12.553 回答