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

前端 未结 7 1582
盖世英雄少女心
盖世英雄少女心 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 19:10

    I find the first example better - less verbose, clearer and more readable.

    In my opinion, go with what best gets your intention across, after all:

    Programs should be written for people to read, and only incidentally for machines to execute.

    -- from "Structure and Interpretation of Computer Programs" by Abelson and Sussman

    By the way, since you're just starting to learn Python, start learning the new String Formatting syntax right away:

    for k, v in os.environ.items():
        print "{0}={1}".format(k, v)
    
    0 讨论(0)
提交回复
热议问题