推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
ry_wang
V2EX  ›  Python

下面的代码有什么更好看的写法么?

  •  
  •   ry_wang ·
    saipanno · Jan 12, 2015 · 3980 views
    This topic created in 4292 days ago, the information mentioned may be changed or developed.
    在写代码的时候遇到下面的问题,截取代码的一段。

    代码的最开始回初始化一个mapping字典,里面定义了一些初始值,但是下面给字典更新值的时候由于在一个列表中要用多次,所以必须得deepcopy一下,请问这块儿代码有什么更好的写法么?
    我能想到的是再定义一个更新函数,把mapping更新的操作包起来。

    谢谢


    4 replies  •  2015-01-12 18:59:08 +08:00
    zhyu
        1
    zhyu  
       Jan 12, 2015   ❤️ 1
    zhyu
        2
    zhyu  
       Jan 12, 2015
    个人意见,避免无意义的重复代码
    keys 应该写在 config 里,便于扩展
    ry_wang
        3
    ry_wang  
    OP
       Jan 12, 2015
    @zhyu enumerate解决了大问题,赞
    另外 {key: v for key in keys} 这样真的可以么?py3?
    zhyu
        4
    zhyu  
       Jan 12, 2015
    @ry_wang dict comprehension 是 python 2.7 加入的,3 也可以
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1315 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:52 · PVG 07:52 · LAX 16:52 · JFK 19:52
    ♥ Do have faith in what you're doing.