为了账号安全,请及时绑定邮箱和手机立即绑定

手动替换列表中的元素

手动替换列表中的元素

猛跑小猪 2021-03-20 19:15:14
例子:a = [1,2,3,2,4,2,5]for key in a:    if key == 2:        key = 10print key结果: [1,10,3,10,4,10,5]我需要Python手动“询问”要替换的元素。
查看完整描述

3 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

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


查看完整回答
反对 回复 2021-03-31
?
达令说

TA贡献1821条经验 获得超6个赞

您正在寻找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]


查看完整回答
反对 回复 2021-03-31
  • 3 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信