Pythonic从字典中增加和分配id的方法
发布时间:2020-09-25 06:17:59 所属栏目:Python 来源:互联网
导读:这似乎是一种非常常见的模式: for row in reader: c1=row[0] if ids.has_key(c1): id1=ids.get(c1) else: currid+=1 id1=currid ids[c1]=currid 我想知道是否有更好的方法来实现这一目标.至于单行if语句,我可以这么
这似乎是一种非常常见的模式: for row in reader: c1=row[0] if ids.has_key(c1): id1=ids.get(c1) else: currid+=1 id1=currid ids[c1]=currid 我想知道是否有更好的方法来实现这一目标.至于单行if语句,我可以这么做: id1=ids.get(c1) if ids.has_key(c1) else currid+1 但是,如果if情况被执行,我就会坚持使用currid和sticking,如果if条件通过,则将c-> id1粘贴到字典中. 解决方法如果id从0开始:for row in reader: id1 = ids.setdefault(row[0],len(ids)) (旁白:has_key被认为已弃用.在d中使用x而不是d.has_key(x).) (编辑:岳阳站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- python – pelican模板中当前页面的URL的变量
- python芹菜max-tasks-per-child-setting默认值
- Python:如何找到使用matplotlib绘制的图形的斜率
- python – pip安装eyeD3模块.找不到libmagic
- python装饰器(新年第一写)
- python – Pandas concat:ValueError:传递值的
- python – 找不到manage.py collectstatic命令,D
- Python:“subprocess.Popen”检查成功和错误
- 如何避免在python中阻塞代码?
- python – 了解matplotlib xticks语法
热点阅读