- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 376字
- 2021-07-02 21:09:32
Comprehension
Python has a special kind of expression called a comprehension. Comprehensions are variations of the special syntax for creating dictionaries, lists, and sets.
Let's look at some examples. Here we see a list comprehension:
capitals = [x.upper() for x in example_list]
What this expression does is that it creates a new list containing the uppercase versions of the words in the old list.
The first part after the opening square bracket is an x.upper() expression. This expression describes how to derive a member of the new list from a member of the old list. After that is the for keyword, then the name of the x variable we used in the first expression to represent the values from the old list. Then, the keyword is followed by the example_list expression that gives us the old list and the closing square bracket. The code output is as follows:

The dictionary and set comprehensions are very similar. If we want to use both the key and the value of an existing dictionary in a comprehension, we need to use the dict.items function, and dictionary comprehensions need to specify both the key and value separated by a colon, as shown in this example:
squares = {k: v ** 2 for k, v in example_dict.items()}
As shown in the following screenshot, notice that the resulting data type depends on what sort of comprehension we used, not on what sort of data structure we used as the source of data:

We can use a list comprehension to create a list of data pulled from the values of a dictionary, for example, or, as we did here, we can use the set comprehension to create a set.
Tuples are slightly different, but only slightly. A tuple comprehension would look exactly like a different syntactic element called a generator expression. The code example for tuple comprehension is as follows:

Python's designers hate ambiguity; so instead, if we want the equivalent of a tuple comprehension, we pass a generator expression to a tuple constructor.
That's it for this quick introduction to Python's built-in data structures. In the next section, we're going to look at some useful, but possibly surprising, traits of functions and classes that are significantly different from C, C++, or Java.
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計
- Visual C++應(yīng)用開發(fā)
- Spring+Spring MVC+MyBatis整合開發(fā)實(shí)戰(zhàn)
- Python Data Analysis Cookbook
- NoSQL數(shù)據(jù)庫原理
- HTML5 APP開發(fā)從入門到精通(微課精編版)
- 從零開始:UI圖標(biāo)設(shè)計與制作(第3版)
- C編程技巧:117個問題解決方案示例
- IBM Cognos TM1 Developer's Certification guide
- Practical GIS
- Mastering OAuth 2.0
- 例說FPGA:可直接用于工程項(xiàng)目的第一手經(jīng)驗(yàn)
- Java 11 and 12:New Features
- 數(shù)據(jù)結(jié)構(gòu)與算法詳解
- 零基礎(chǔ)學(xué)西門子PLC編程:入門、提高、應(yīng)用、實(shí)例