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

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

    If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer.

    If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.

提交回复
热议问题