程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

用字典更改列表中的项目

发布于2019-12-26 01:58     阅读(1453)     评论(0)     点赞(18)     收藏(0)


dic = {'a':'1','b':'2'}
lis = ['a','b']
for c in lis:
    c = dic[c]
print lis

列表未更改。我曾期望该列表将更改为['1','2']谁能解释?


解决方案


尝试使用索引而不是变量...

for i in range(len(li)):
    c = li[i]
    li[i] = dic[c]
print li

另外,不要使用list作为变量名..
或用enumerate

for i, c in enumerate(li):
    li[i] = dic[c]
print li

或列出理解

lis = [dic[c] if c in dic else c for c in lis]

为什么不做什么呢?
当使用时for x in y:xy
So中获取对象/项目的值,因此,如果更改的值x,则不会更改的值y[i]i即您所在的索引。

所以,如果你这样做

>>> y = range(5,10)
>>> for x in y:
    i = y.index(x)
    x += 10
    print i
    print 'Value of x    : %3d, id: %7d' % (x, id(x))
    print 'Value of y[i] : %3d, id: %7d' % (y[i], id(y[i]))
    print '-'*31

你会看到差异



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/185700/040fc71e08b24c4ca54e/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)