It took more than ten years to figure out: the essence of Python is actually square brackets, curly brackets and parentheses!

Tianyuan prodigal son 2020-11-13 09:06:16
took years figure essence python


Compared with other programming languages , What is Python Unique features ? Many programmers will say , Indent . You bet , Indentation is Python The symbolic features of language , But it's just external 、 In form . From the aspect of language characteristics ,Python What are the characteristics of ? I tried to search on Zhihu , The most representative answers are Grammatical simplicity Easy to learn Code efficiency Powerful And so on . Savor these four items carefully , I still think , This is a Python The effect or user feeling of language , It's still not a feature of language features .

Another way , Is it Python What linguistic features of the language make people generally believe that Python With concise grammar 、 Easy to learn 、 Code efficiency 、 Powerful features ? I personally think , Thanks to the list (list)、 Dictionaries (dict)、 Tuples (tuple) And collection (set) this “ Four King Kong ”. Despite the integer (int)、 floating-point (float) And string (str) It's also important. , But these three objects are relative to other programming languages , The difference is not like “ Four King Kong ” So obvious . It is no exaggeration to say , list 、 Dictionaries 、 Tuples and sets represent Python The core and foundation of language , It's also Python The essence of . Learn to use lists 、 Dictionaries 、 Tuples and sets , It means mastering Python This programming language .

If you accept this view , that ,Python The essence of this is from the list 、 Dictionaries 、 Tuples and sets, etc “ Four King Kong ”, It evolved into square brackets 、 It's made up of curly brackets and round brackets “ Bracket family ”.

1. square brackets

Square brackets are the first symbol of almost all programming languages . The first one here , It's not about the frequency of use , It refers to the meaning and creativity of programming language shown by this symbol . in fact , In terms of the frequency of use of symbols , Square brackets may also come first —— It's just my intuition , There is no statistical support for .

1.1 Create a list of

For beginners , The most common way to create a list is to use square brackets .

>>> a = []
>>> a
[]
>>> b = [3.14, False, 'x', None]
>>> b
[3.14, False, 'x', None]

Even old birds , You also use a lot of square brackets to create lists , Especially when you use derivation to create lists .

>>> c = [i**2 for i in range(5)]
>>> c
[0, 1, 4, 9, 16]

But I always felt , Square brackets are like colloquial or slang , Too casual . I prefer to use rigorous list() To create a list . Use list() Create a list of , yes list The standard method of instantiation of a class , You can feel list How does the constructor of a class adapt to different types of parameters .

>>> a = list()
>>> a
[]
>>> b = list((3.14, False, 'x', None))
>>> b
[3.14, False, 'x', None]
>>> c = list({
1,2,3})
>>> c
[1, 2, 3]
>>> d = list({
'x':1,'y':2,'z':3})
>>> d
['x', 'y', 'z']
>>> e = list(range(5))
>>> e
[0, 1, 2, 3, 4]
>>> f = list('*'*i for i in range(5))
>>> f
['', '*', '**', '***', '****']

1.2 Index of the list

Square brackets create lists , But square brackets are not the same as lists , Because square brackets are also used for indexing .

>>> [3.14, False, 'x', None][2]
'x'
>>> [3.14, False, 'x', None][-2]
'x'
>>> [3.14, False, 'x', None][1:]
[False, 'x', None]
>>> [3.14, False, 'x', None][:-1]
[3.14, False, 'x']
>>> [3.14, False, 'x', None][::2]
[3.14, 'x']
>>> [3.14, False, 'x', None][::-1]
[None, 'x', False, 3.14]

The index of the list is very flexible , In particular, the introduction of negative index , use -1 Represents the last element or reverse order , It's a big rush . Operation above , It belongs to the common index mode , If you can read the following code , It means that you have enough skill .

>>> a = [3.14, False, 'x', None]
>>> a[2:2] = [1,2,3]
>>> a
[3.14, False, 1, 2, 3, 'x', None]

1.3 List method

For the list object method, if you can use it at your fingertips , That's it Python Master .

>>> a = [3.14, False, 'x', None]
>>> a.index('x')
2
>>> a.append([1,2,3])
>>> a
[3.14, False, 'x', None, [1, 2, 3]]
>>> a[-1].insert(1, 'ok')
>>> a
[3.14, False, 'x', None, [1, 'ok', 2, 3]]
>>> a.remove(False)
>>> a
[3.14, 'x', None, [1, 'ok', 2, 3]]
>>> a.pop(1)
'x'
>>> a
[3.14, None, [1, 'ok', 2, 3]]
>>> a.pop()
[1, 'ok', 2, 3]
>>> a
[3.14, None]

2. Curly braces

Curly brackets represent dictionary objects , Most beginners think so . However , This is wrong , At least one-sided . In the following code ,a and b They're all objects created with curly braces , But one is a dictionary , One is a collection .

>>> a = {
}
>>> a
{
}
>>> b = {
'x','y','z'}
>>> b
{
'y', 'z', 'x'}
>>> type(a)
<class 'dict'>
>>> type(b)
<class 'set'>

original ,Python Use curly brackets to represent dictionary and collection objects : The curly brackets are empty , Or key value pairs , A dictionary ; There are no repeating elements in curly brackets , Represents a collection . In order not to cause misunderstanding , I used to dict() To generate a dictionary , use set() To generate collections .

>>> dict()
{
}
>>> dict({
'x':1, 'y':2, 'z':3})
{
'x': 1, 'y': 2, 'z': 3}
>>> dict((('x',1), ('y',2), ('z',3)))
{
'x': 1, 'y': 2, 'z': 3}
>>> dict.fromkeys('xyz')
{
'x': None, 'y': None, 'z': None}
>>> dict.fromkeys('abc', 0)
{
'a': 0, 'b': 0, 'c': 0}
>>> set((3,4,5))
{
3, 4, 5}
>>> set({
'x':1, 'y':2, 'z':3})
{
'y', 'z', 'x'}
>>> set([3,3,4,4,5,5])
{
3, 4, 5}

In coding practice , Although in some cases sets are irreplaceable , But the frequency of the set is “ Four King Kong ” The lowest of all , We don't have a discussion here , Just talk about the use of dictionaries .

2.1 Determine whether a key exists in the dictionary

Py2 Time ,dict The object used to have has_key() Methods , Used to determine whether a key is included .py3 Abandoned this method , Determine whether a key exists in the dictionary , Only use in In this way .

>>> a = dict({
'x':1, 'y':2, 'z':3})
>>> 'x' in a
True
>>> 'v' in a
False

2.2 Add a new key to the dictionary or update the key value

Many people like to assign a key to a dictionary , Add a new key to the dictionary or update the key value .

>>> a = dict()
>>> a['name'] = 'xufive'
>>> a
{
'name': 'xufive'}

I don't recommend this way , Use update() It's more ritualistic , You can also add or modify multiple keys at once .

>>> a = dict()
>>> a.update({
'name':'xufive', 'gender':' male '})
>>> a
{
'name': 'xufive', 'gender': ' male '}

2.3 Get a key value from a dictionary

a[‘age’] It's the most common way , But there are also exceptions where the key does not exist . The following method is worth recommending .

>>> a.get('age', 18)
18

2.4 Get all keys of dictionary 、 All values 、 All key value pairs

dict Class provides keys()、values() and items() The three methods return all the keys of the dictionary respectively 、 All value and all key value pairs . It should be noted that , The returned result is not a list , It's an iterator . If you need to return results in tabular form , Please use list() transformation .

>>> a = dict()
>>> a.update({
'name':'xufive', 'gender':' male '})
>>> list(a.keys())
['name', 'gender']
>>> list(a.values())
['xufive', ' male ']
>>> list(a.items())
[('name', 'xufive'), ('gender', ' male ')]

2.5 Ergodic dictionary

When traversing the dictionary , Many students have written it as traversal dictionary keys(). Actually , It doesn't need to be that much trouble , You can traverse directly as follows .

>>> a = dict([('name', 'xufive'), ('gender', ' male ')])
>>> for key in a:
print(key, a[key])
name xufive
gender male

3. parentheses

Parentheses represent tuple objects , So there should be no problem ? You bet , It doesn't sound like a problem , But in the use of tuples , I believe every beginner will fall into the same pit at least once .

3.1 We must go into the shallow pit

Tuples are not used for the most salient feature of lists , The value of the element cannot be updated . Forget or ignore this , It's going to go into the pit .

>>> a = (3, 4)
>>> a[0] = 5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
a[0] = 5
TypeError: 'tuple' object does not support item assignment

3.2 You must go into the pit

It has been used for many years Python after , Write the worst I ever had bug, This is the following code .

>>> import threading
>>> def do_something(name):
print('My name is %s.'%name)
>>> th = threading.Thread(target=do_something, args=('xufive'))
>>> th.start()
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\xufive\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
TypeError: do_something() takes 1 positional argument but 6 were given

I clearly only provided 1 Parameters , But the hint is that it gives 6 Parameters , Why? ? original , When tuples are initialized , If there is only a single parameter , You must add a comma after a single parameter (,), otherwise , The initialization result only returns the original parameter .

>>> a = (5)
>>> a
5
>>> type(a)
<class 'int'>
>>> b = ('xyz')
>>> b
'xyz'
>>> type(b)
<class 'str'>
>>> a, b = (5,), ('xyz',)
>>> a, b
((5,), ('xyz',))
>>> type(a), type(b)
(<class 'tuple'>, <class 'tuple'>)

3.3 Single asterisk unpacking tuple

When formatting the output string ,C Language style is my favorite . When there is more than one % When matching is required , The following is perhaps the most natural way to write .

>>> args = (95,99,100)
>>> '%s: Chinese language and literature %d branch , mathematics %d branch , English %d branch '%(' Tianyuan prodigal son ', args[0], args[1], args[2])
' Tianyuan prodigal son : Chinese language and literature 95 branch , mathematics 99 branch , English 100 branch '

Right is right , But it's not good enough . The full score should be like this .

>>> args = (95,99,100)
>>> '%s: Chinese language and literature %d branch , mathematics %d branch , English %d branch '%(' Tianyuan prodigal son ', *args)
' Tianyuan prodigal son : Chinese language and literature 95 branch , mathematics 99 branch , English 100 branch '

3.4 Why use tuples ?

Since the element of the tuple is immutable , So why use tuples ? Isn't it more convenient to use lists instead of tuples ? indeed , In most cases , You can use lists instead of tuples , But the following example proves that , Lists can't replace tuples .

>>> s = {
1,'x',(3,4,5)}
>>> s
{
1, (3, 4, 5), 'x'}
>>> s = {
1,'x',[3,4,5]}
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
s = {
1,'x',[3,4,5]}
TypeError: unhashable type: 'list'

We can add tuples to the set , But lists don't work , Because the list is not hashable (unhashable) Of . It's not difficult to understand that : List elements can be changed dynamically , So there is no fixed hash value —— This conflicts with the element uniqueness required by the set ; Elements of tuples are not allowed to be updated , Its hash value does not change throughout its life cycle , So it can be an element of a collection .

obviously , Tuples and lists are stored in a completely different way . Because you don't have to think about updates , Tuples are much faster than lists . Tuples are preferred , Should be Python A basic principle that programmers follow .

版权声明
本文为[Tianyuan prodigal son]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database