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

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).

主站蜘蛛池模板: 金寨县| 乃东县| 巨野县| 射阳县| 馆陶县| 建湖县| 桐梓县| 桦南县| 广饶县| 西畴县| 东港市| 石城县| 邵阳县| 辉南县| 巴彦淖尔市| 建阳市| 鹤岗市| 铅山县| 贡嘎县| 页游| 石棉县| 蛟河市| 安溪县| 个旧市| 彰化县| 伊春市| 南和县| 高青县| 金沙县| 浙江省| 星子县| 榆社县| 马山县| 方山县| 旌德县| 潮州市| 鄢陵县| 视频| 花莲市| 龙井市| 资溪县|