手动替换列表中的元素

例子:


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


猛跑小猪
浏览 164回答 3
3回答

萧十郎

>>> 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]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python