官术网_书友最值得收藏!

Comprehensions

Python comprehensions, commonly known as list comprehensions, are a very powerful Python utility that comes in handy if we need to perform some manipulation operations over all or some of the elements of a list. A list comprehension would return a new list with the modifications applied. Let's say that we have a  list of numbers and we want to square each number in the list.

Let's take a look at two different approaches to this problem:

The code snippet on the left, the more traditional approach, took nine lines. The same code using comprehensions took us just three lines. A list comprehension is declared within square brackets and it performs any operation on each element of a list. It then returns a new list with the modifications. Let's take a look at another example of comprehensions. This time, we will use an if condition (known as a comprehension filter), and nested loops with comprehensions. We will name the file list_comp_adv.py and enter the following code:

The preceding snippet is self-explanatory. It shows us how to use if conditions with comprehensions (line 4). It also shows us how to use nested loops to add up two lists (line 5). Finally, it shows us how to use dictionaries with comprehensions (line 6).

主站蜘蛛池模板: 永寿县| 工布江达县| 虎林市| 和田市| 阳西县| 萝北县| 汕尾市| 册亨县| 正镶白旗| 麻城市| 海丰县| 八宿县| 颍上县| 呼玛县| 绵竹市| 安达市| 和田市| 嘉鱼县| 香港| 枣强县| 辉县市| 时尚| 阜阳市| 济源市| 曲靖市| 神农架林区| 阿城市| 聊城市| 宜州市| 大理市| 景宁| 禄劝| 沙湾县| 周宁县| 邵阳市| 崇明县| 大冶市| 镇原县| 昭苏县| 汶川县| 微博|