- Hands-On Penetration Testing with Python
- Furqan Khan
- 214字
- 2021-07-02 14:13:56
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).
- Python程序設計教程(第2版)
- 在最好的年紀學Python:小學生趣味編程
- Getting Started with React
- Building a Home Security System with Raspberry Pi
- 數據結構和算法基礎(Java語言實現)
- VMware vSphere 6.7虛擬化架構實戰指南
- Gradle for Android
- 區塊鏈項目開發指南
- Mastering Concurrency Programming with Java 9(Second Edition)
- Android從入門到精通
- 基于Docker的Redis入門與實戰
- 大象:Thinking in UML(第二版)
- Scratch 3.0少兒積木式編程(6~10歲)
- A/B 測試:創新始于試驗
- C/C++程序設計教程:面向過程分冊