"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

In the last article "Learning Python with You Hand in Hand" 22-Dictionary , we learned the basic concepts of dictionaries, the methods of adding , deleting, modifying, checking, dictionary functions and several more important methods. In this article, we will first introduce a few built-in sequence functions in Python, and then introduce a few examples of dictionaries, so that you can better grasp the characteristics of dictionaries and the application methods in programming.

1. sorted() function

The function of sorted() is to sort the elements in any sequence in positive order and create a sorted list for output. The parameter of the function is an arbitrary sequence. When sorting, it will be split according to the smallest unit that can be traversed, and then sorted. When we studied lists before, there was a list.sort() method, similar to this.

In [1]: sorted("《手把手陪您学Python》")   # 字符串排序的输出结果,是由每个字符排序后作为元素的列表
Out[1]: ['P', 'h', 'n', 'o', 't', 'y', '《', '》', '学', '您', '手', '手', '把', '陪']

In [2]: sorted((8, 5, 1))
Out[2]: [1, 5, 8]

In [3]: sorted((8, 5, (1, 2)))    # 参数中要排序的元素必须只能是一种数据类型,否则会报错
Out[3]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-9-d3c8864d6278> in <module>
        ----> 1 sorted((8, 5, (1, 2)))    # 参数中要排序的元素必须只能是一种数据类型,否则会报错
        
        TypeError: '<' not supported between instances of 'tuple' and 'int'

In [4]: sorted(((8, 5), (1, 2)))   # 可以都是元组或者列表
Out[4]: [(1, 2), (8, 5)]

In [5]: sorted({3:'A', 2:'B', 1:'C'})   # 字典按照键进行排序,输出时也只输出键排序后的列表
Out[5]: [1, 2, 3]

In [6]: sorted(123)   # 数字不能排序,因为数字不能被遍历
Out[6]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-13-2b4e23a052ca> in <module>
        ----> 1 sorted(123)   # 单个数字不能排序,因为数字不能被遍历
        
        TypeError: 'int' object is not iterable

 2. The reversed() function

The function of reversed() is to arrange the elements of the sequence in reverse order. But don't think that the difference between it and the sorted() function is only the positive order and the reverse order. In fact, there is still a big difference.

One is that the sorted() function sorts the elements in the sequence according to the ASCII order in the positive order, while the reversed() function does not reorder the elements in the sequence in ASCII, but directly arranges the original sequence in reverse order. It's easier to misunderstand it, and you can understand it by looking at an example.

In [7]: print(sorted("《手把手陪您学Python》"))   # 整体重排序
        print(list(reversed("《手把手陪您学Python》")))   # 将原来的顺序倒过来
Out[7]: ['P', 'h', 'n', 'o', 't', 'y', '《', '》', '学', '您', '手', '手', '把', '陪']
        ['》', 'n', 'o', 'h', 't', 'y', 'P', '学', '您', '陪', '手', '把', '手', '《']

 The second is that the sorted() function can reorder the sequence and output it in the form of a list, while the reversed() function generates only an iterator. If you directly output the result of reversed(), it will report an error (not an error to be precise, write here It will be easier to understand), you need to use the list() function to convert it into a list (as in the example above). Using this feature of the reversed() function, it can be used directly as an iterator in a for loop.

In [8]: reversed("《手把手陪您学Python》")   # 直接输出会报错
Out[8]: <reversed at 0x1c6f3f12898>

In [9]: for str in reversed("《手把手陪您学Python》"):   # 可以作为for循环的迭代器
            print(str, end=' ')   # 注意print()函数的参数
Out[9]: 》 n o h t y P 学 您 陪 手 把 手 《

 3. Enumerate() function

When we traverse a sequence, we not only traverse every element in the sequence, but sometimes also need to record the position of each element in the sequence at the same time. Using what we have learned, we can write code like this:

In [10]: lst = ['A', 'B', 'C', 'D', 'E', 'F']
         i = 0
         for value in lst:
             i += 1   # 还记得这个符号吧
             print("序列中,第{}个元素是{}".format(i, value))
Out[10]: 序列中,第1个元素是A
         序列中,第2个元素是B
         序列中,第3个元素是C
         序列中,第4个元素是D
         序列中,第5个元素是E
         序列中,第6个元素是F

Since this situation is very common, there is a built-in enumerate() function in Python to directly obtain the elements and positions of the sequence. The result of the return value is a tuple of (i, value), where value is the value of the element and i is the position index of the element. Please note that in the output result, the order of i and value is immutable. Pay special attention when naming variables.

Using the enumerate() function, the previous example can be abbreviated as the following code:

In [11]: lst = ['A', 'B', 'C', 'D', 'E', 'F']
         for i, value in enumerate(lst):   # 变量名即使颠倒,元素的索引也会赋值给前面的变量,元素值也会赋值给后面的变量
             print("序列中,第{}个元素是{}".format(i, value))
Out[11]: 序列中,第1个元素是A
         序列中,第2个元素是B
         序列中,第3个元素是C
         序列中,第4个元素是D
         序列中,第5个元素是E
         序列中,第6个元素是F

Seeing this, everyone can know that the function of the enumerate() function is actually to output a binary tuple, and this binary tuple happens to be very similar to the key-value pair of a dictionary. Therefore, we can use the enumerate() function to construct a dictionary and map the index value and element value to the dictionary.

In [12]: lst = ['A', 'B', 'C', 'D', 'E', 'F']   # 构造序列
         dict0 = {}   # 定义空字典,必须要定义,否则报错
         for i, value in enumerate(lst):
             dict0[i] = value
         dict0
Out[12]: {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}

 The above is an example of using sequence index values ​​as dictionary keys and element values ​​as dictionary values. You can try to find out how to use element values ​​as dictionary keys and sequence index values ​​as dictionary values.

4. The zip() function

The function of the zip() function is to pair the elements of a list, tuple or other sequence according to the index order, and generate a list of tuples. The matched sequence can be of different types. When the sequence length is different, the final output list length is determined by the shortest sequence.

In [13]: seq1 = ['A', 'B', 'C', 'D', 'E']   # 列表元素为字符串
         seq2 = (1, 2, 3, 4, 5, 6)   # 元组元素为数字,有6个元素,但输出结果以最短的5个元素为准
         seq3 = [(1, 2), (1, 2) , (1, 2), (1, 2), (1, 2)]   # 列表元素为元组
         seq4 = (1, [1, 2], 'W', (1, 2), True)   # 元组包括多种元素类型
         zipped1 = zip(seq1, seq2, seq3, seq4)   # 序列类型和序列内的元素类型都可以不同
         list(zipped1)    # 转换成列表显示
Out[13]: [('A', 1, (1, 2), 1),
          ('B', 2, (1, 2), [1, 2]),
          ('C', 3, (1, 2), 'W'),
          ('D', 4, (1, 2), (1, 2)),
          ('E', 5, (1, 2), True)]

In [14]: seq5 = ['A', 'B', 'C', 'D', 'E']   # 列表
         seq6 = (1:11, 2:22, 3:33, 4:44, 5:55)   # 字典
         zipped2 = zip(seq5, seq6)   # 字典不能和其它配对,字典间也不能配对
         list(zipped2)
Out[14]: File "<ipython-input-25-6db62aa22811>", line 2
             seq6 = (1:11, 2:22, 3:33, 4:44, 5:55)   # 字典
                      ^
         SyntaxError: invalid syntax

A common scenario of the zip() function is to traverse multiple sequences at the same time, sometimes used with the enumerate() function.

 

In [15]: for i, (a, b, c, d) in enumerate(zip(seq1, seq2, seq3, seq4)):
             print("{0} : {1}, {2}, {3}, {4}".format(i, a, b, c, d))   # 格式化输出的方式,大家还记得吧
Out[15]: 0 : A, 1, (1, 2), 1
         1 : B, 2, (1, 2), [1, 2]
         2 : C, 3, (1, 2), W
         3 : D, 4, (1, 2), (1, 2)
         4 : E, 5, (1, 2), True

In addition to "pairing" sequences, the zip() function can also intelligently "split" a sequence similar to "paired", and this "paired" sequence is not necessarily a list, but can also be a tuple And other sequences. The function used is still the zip() function, but an * sign must be added before the parameter to become zip(*). You can understand it as the inverse process of zip, or as the "decompression" process.

In [16]: seq1, seq2, seq3, seq4 = zip(*zip(seq1, seq2, seq3, seq4))   # 利用“解压”过程,可以将配对后的序列再进行还原
         print('seq1: ', seq1, '\nseq2: ', seq2,'\nseq3: ', seq3,'\nseq4: ', seq4)
Out[16]: seq1:  ('A', 'B', 'C', 'D', 'E')
         seq2:  (1, 2, 3, 4, 5)
         seq3:  ((1, 2), (1, 2), (1, 2), (1, 2), (1, 2))
         seq4:  (1, [1, 2], 'W', (1, 2), True)

In [17]: seq = [(1, 'A'), (2, 'B'), (3, 'C')]   # 换个列子能看清楚一些,相当于把行的列表,变成列的列表
         a, b = zip(*seq)
         print(a, '\n', b)
Out[17]: (1, 2, 3)
         ('A', 'B', 'C')

Through two examples, do you already understand the function of zip(*)? The function of zip() is to merge elements at the same position in multiple sequences into tuples, and then merge them into a list. The function of zip(*) is to combine the elements at the same position in each tuple in the list into multiple tuples. (The explanation is a bit obscure, you can look at the examples for comparison)

5. Generate a dictionary from the sequence

If there are two sequences, I hope that these two sequences can be paired according to the position of the element in the dictionary (one sequence provides the key and the other sequence provides the value), using the zip() function can write such code:

In [18]: key_list = (1, 2, 3)
         value_list =  ('A', 'B', 'C')
         dict1 = {}
         for key, value in zip(key_list, value_list):
             dict1[key] = value
         dict1
Out[18]: {1: 'A', 2: 'B', 3: 'C'}

Since the dictionary is essentially a collection of 2-tuples (tuples containing 2 tuples), the dictionary can accept a list of 2-tuples as parameters, so it is not necessary to use the for loop in the list after zip() To traverse, and directly generate a dictionary:

In [19]: key_list = (1, 2, 3)
         value_list =  ('A', 'B', 'C')
         dict2 = dict(zip(key_list, value_list))
         dict2
Out[19]: {1: 'A', 2: 'B', 3: 'C'}

The above is the introduction to the 4 built-in sequence functions in Python. Some dictionary applications are also interspersed in it, which also supplements the dictionary introduced in the previous article.

In the next article, we will continue to learn the data structure of Python. What we will introduce to you is the collection, which is also the last data structure we learn at this stage, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

For Fans: Follow the "also said Python" public account, reply "hand 23", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/102668953