In Python, is it better to use list comprehensions or for-each loops?

前端 未结 7 1692
盖世英雄少女心
盖世英雄少女心 2020-11-27 18:41

Which of the following is better to use and why?

Method 1:

for k, v in os.environ.items():
       print \"%s=%s\" % (k, v)

Method 2

7条回答
  •  天命终不由人
    2020-11-27 18:48

    I agree with @Ben, @Tim, @Steven:

    • readability is the most important thing (do "import this" to remind yourself of what is)
    • a listcomp may or may not be much faster than an iterative-loop version... it depends on the total number of function calls that are made
    • if you do decide to go with listcomps with large datasets, it's better to use generator expressions instead

    Example:

    print "\n".join("%s=%s" % (k, v) for k,v in os.environ.iteritems())
    

    in the code snippet above, I made two changes... I replaced the listcomp with a genexp, and I changed the method call to iteritems(). [this trend is moving forward as in Python 3, iteritems() replaces and is renamed to items().]

提交回复
热议问题