[Python learning manual notes] 002. Python core data types

Gao Yang, who would not be named 2020-11-14 17:27:43
python learning manual notes python


python Core data type

*

This series of articles is my personal study 《python Learning manual ( The fifth edition )》 Learning notes of , Most of them are the summary and personal understanding of the book , A small part of the content is the extension of relevant knowledge points .

For non-commercial use, please indicate the author and source ; Please contact me for commercial use (gaoyang1019@hotmail.com) Get permission .

*

Let's deal with something that we don't understand in the book first , Literal

Baidu Encyclopedia gives a literal explanation :" In computer science , Literal (literal) Is used to express a fixed value in the source code (notation)."

I said I didn't understand , And then I checked . The so-called literal quantity , It's the numbers, strings and so on after the equal sign of assignment . So give a qualitative explanation .

var = 10 # This "10" It's literal 

python Built in objects for

object type Literal / Construction examples
Numbers 1234, 3.1415
character string "hello" b'a\x01c'
list [1,2,"word"], list(range(10))
Dictionaries {"food":"tomato","price":6.66}, dict(hours=10)
Tuples (1,2,"brady"),tuple('spam')
file open("egg.txt")
aggregate set("abc"),{'a','b','c'}
Other core types type ,None, Boolean type
Program unit type function , modular , class
Python Implement related types Compiled code , Call stack trace

Numeric type

Python The number type in , In addition to supporting common integers and floating-point numbers , There are also appendages with imaginary parts , Fixed precision decimal number , Rational numbers with numerator and denominator and so on . Support common arithmetic operations .

character string

Strings are passed through "" perhaps '' Any text enclosed . stay python Single quotation marks and double quotation marks have the same function .

First of all, we should understand the two characteristics of string :

  • python The string in is a sequence , In other words, it follows an iterative protocol
  • A string is an unchangeable quantity ( This is a little difficult to understand , I'll say later , Let's admit it first )

Operation of string sequence

adopt len() Method to calculate the length

In [2]: S = "spam"
In [3]: len(S)
Out[3]: 4

Index and slice

  1. A string is a sequence , Support index and for The traversal

    In the index of a string , A negative number is a reverse index , That is, from back to front . in other words S[-1] amount to S[len(S)-1]

    In [4]: S[0]
    Out[4]: 's'
    In [5]: S[-1]
    Out[5]: 'm'
    In [6]: for s in S:
       ...:     print(s)
       ...:
    s
    p
    a
    m
  2. String supports fragment operation

    In [7]: S='hello'
    #  Take the substring between the third and the fifth
    In [8]: S[2:4]
    Out[8]: 'll'
    #  From the third to the end
    In [9]: S[2:]
    Out[9]: 'llo'
    #  Take the top three
    In [10]: S[:3]
    Out[10]: 'hel'
    #  From the beginning of the intercept to before the penultimate
    In [11]: S[:-2]
    Out[11]: 'hel'

    Be careful , During the slicing operation ,X[I:J] It means from X[I] Start , To X[J] end , But not including X[J]

  3. String splicing and repetition

    String support through + Connect . It can also be done through * Repeat .

    But notice , It doesn't mean that strings can be changed . For example, the following code 3-4 In line ,S+'xyz'.

    This is not a change to the original string S, It's about opening up new memory space , The original string S and 'xyz' Connect , Generate a new quantity .

    In [12]: S = "spam"

    In [13]: S+'xyz'
    Out[13]: 'spamxyz'

    In [14]: S*3
    Out[14]: 'spamspamspam'

    here , For operators + There are different types of things that work . For example, in the number type, it means the addition in arithmetic operation , To represent a string connection in a string . This characteristic is the legendary polymorphism , Also known as operator overloading . This is a Python One of the most important design ideas in .

Immutability

The string is in Python Chinese is an immutable literal quantity . stay python In the core type , character string , Numbers , Tuples are immutable . The list of , Dictionaries , The set is variable .

Of course , Through the previous study , Some operations , As if you could change the string . But the point here is , This so-called " change " character string , It's actually generating new literals , Instead of changing the original literal amount .

The method of feature type ( Built-in methods )

Python For different types , Built in some convenient ways to use . That's what we call built-in methods . Related built-in methods can be found in python Documents on the official website The query . This is part of what we're going to learn later .

In [15]: S = "Spam"
#  String substitution
In [17]: S.replace('pa','xz')
Out[17]: 'Sxzm'
    
In [18]: line = "aaa,bbb,ccc"
#  String segmentation
In [19]: line.split(',')
Out[19]: ['aaa''bbb''ccc']

stay python in , We can go through dir() Method to view in its scope , The properties and methods supported by this type .

In [20]: dir(S)
Out[20]:['__add__''__class__''__contains__''__delattr__''__dir__''__doc__''__eq__''__format__''__ge__''__getattribute__''__getitem__''__getnewargs__''__gt__''__hash__''__init__''__init_subclass__''__iter__''__le__''__len__''__lt__''__mod__''__mul__''__ne__''__new__''__reduce__''__reduce_ex__''__repr__''__rmod__''__rmul__''__setattr__''__sizeof__''__str__''__subclasshook__''capitalize''casefold''center''count''encode''endswith''expandtabs''find''format''format_map''index''isalnum''isalpha''isascii''isdecimal''isdigit''isidentifier''islower''isnumeric''isprintable''isspace''istitle''isupper''join''ljust''lower''lstrip''maketrans''partition''replace''rfind''rindex''rjust''rpartition''rsplit''rstrip''split''splitlines''startswith''strip''swapcase''title''translate''upper''zfill']

Escape characters and unicode character string

python Like any other language , Support '\' The escape character of . For example, the common \n and \t

in addition python Native support unicode character string . ( About unicode character string , There will be related articles in the future )

list

The list is similar to C In language, an array of things . But compared to the C An array of languages ,python The list is more flexible :

  • python The list is not limited to the data types within it . Different types of data can be stored in the same list
  • python The list is variable length .
  • python The list supports derived expressions
# python Of   Different data types can be stored in the list 
In [23]: L = [1,2,'egg']

In [24]: len(L)
Out[24]: 3
#  Lists also support splicing operations
In [25]: L + [4,5,6]
Out[25]: [12'egg'456]
#  Lists also support repeating operations
In [26]: L*2
Out[26]: [12'egg'12'egg']

Boundary checking of lists

python There is no fixed size for the list of , But there are also boundary checks , References to non-existent elements are not allowed . in other words , Indexes outside the end of the list are not supported .

In [27]: L = [1,2,3]

In [28]: L[3]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-28-28c5e42e8527> in <module>
----> 1 L[3]

IndexError: list index out of range

If we need to add elements to the list , You can use the built-in method append

In [29]: L[3]=4
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-29-3e20e34dcd62> in <module>
----> 1 L[3]=4

IndexError: list assignment index out of range

In [30]: L.append(4)

In [31]: L
Out[31]: [1234]

List derivation

This is it. python Strong place , In addition to the list can store known , In addition to the actual data , You can also use formulas to generate a list . This is very useful in matrix processing .

In [32]: M = [[1,2,3],[4,5,6],[7,8,9]]

In [33]: M
Out[33]: [[123], [456], [789]]

In [36]: diag=[M[i][i] for i in [0,1,2]]
In [37]: diag
Out[37]: [159]
#  The legendary list generation     
In [38]: L = [[x,x/2,x*2for x in range(-6,7,2if x>0]

In [39]: L
Out[39]: [[21.04], [42.08], [63.012]]

Dictionaries

Dictionaries have many names , Dictionaries , hash , Hash list , Mapping, etc . A dictionary is not a sequence , It's a kind of mapping . It's through the key - Value pairs to store data .

It's stored differently from lists . In short , The storage of the dictionary is the key (key) Conversion by hash function , Get an address , Then set the value (value) Put the address .

That means , The query speed of a dictionary is independent of its size . So for search , Dictionaries are more suitable than lists .

The structure of a dictionary

Here are three ways to construct a dictionary .

In [42]: bob = {'name':'bob','age':40,'job':'dev'}

In [43]: bob
Out[43]: {'name''bob''age'40'job''dev'}

In [44]: bob2 = dict(name='bob',age=40,job='dev')

In [45]: bob2
Out[45]: {'name''bob''age'40'job''dev'}

In [46]: bob3 = dict(zip(['name','job','age'],['bob','dev',40]))

In [47]: bob3
Out[47]: {'name''bob''job''dev''age'40}

About zip() Method usage , The following article will talk about

The values in the dictionary can be simple numbers and strings , It can also be other types of , such as :

In [48]: bob4 = {'name':{"first":'bob','last':'Smith'},'job':['dev','test'],'age':40}

In [49]: bob4
Out[49]: {'name': {'first''bob''last''Smith'}, 'job': ['dev''test'], 'age'40}

Key to dictionary

The key of a dictionary is its index , We can access the corresponding data through the key , You can also add new data through the key . But for keys that don't exist , Access is also not supported .

In [50]: abc = {'A':'a','B':'b','C':'c'}

In [51]: abc['B']
Out[51]: 'b'

In [52]: abc['D']='d'

In [53]: abc
Out[53]: {'A''a''B''b''C''c''D''d'}

In [54]: abc['E']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-54-15e1b0b37eaa> in <module>
----> 1 abc['E']

KeyError: 'E'

So before accessing the dictionary data , To avoid this kind of mistake , We can check if the key we want to access exists .

Let's start with the easiest way to understand , adopt if sentence Inspection

In [57]: if 'D' in abc:
    ...:     print('hit')
    ...: if not 'F' in abc:
    ...:     print('miss')
    ...:
hit
miss

Second, you can use get Method to check , About get Method , Make a simple explanation .

dict.get(key, default=None) get Methods can access data through keys , If not, the second parameter is returned .

In [58]: value = abc.get('D',0)

In [59]: value
Out[59]: 'd'

In [60]: value = abc.get('F',0)

In [61]: value
Out[61]: 0

in addition , Dictionaries also support the adoption of keys Method returns an iteratable object containing all keys .

In [67]: Ks = abc.keys()

In [71]: for key in Ks:
    ...:     print(key)
    ...:
A
B
C
D

Tuples

python The tuple in can be understood as an immutable list . A set of defined elements . The grammar is very simple . as follows :

In [72]: T1 = (1,2,3)

In [73]: type(T1)
Out[73]: tuple

In [74]: T1[1]
Out[74]: 2

In [77]: T1.count(2)
Out[77]: 1

In [78]: T1 +(4,5,6)
Out[78]: (123456)

Tuples also support fragmentation and indexing like lists . But tuples don't support append Other methods . Not exactly , Tuple is more like a storage of any type " character " strand .

that , Now that we have a list , Why do we need tuples ?

The main difference between tuples and lists is , Tuples are immutable . In some specific situations , Tuples provide an integrity constraint .

file

File is a special type , There is no specific literal to create a file . We usually go through open Function passes a file name and operator to generate a file handle .

In [79]: f = open('data.txt','wb')

In [81]: f.write(b'hello world')
Out[81]: 11

In [83]: f.close()

aggregate

python Set is not a sequence , It's not a mapping either . It is python So far , The only kind of unordered set of immutable objects . Actually python In fact, the set in mathematics is called set . Yes , It's the intersection of our junior high school study , And what kind of things .

There are two ways to create a collection :

In [85]: X = {1,2,3,4}

In [87]: Y = set([3,4,5,6])

In [88]: X
Out[88]: {1234}

In [89]: Y
Out[89]: {3456}
#  intersection
In [90]: X&Y
Out[90]: {34}
#  Combine
In [91]: X|Y
Out[91]: {123456}
#  Difference set
In [92]: X-Y
Out[92]: {12}
# X Is it Y Superset
In [93]: X>Y
Out[93]: False

Other data types

In addition to the core types described above ,python There are also data types in :

  • class
  • Code block
  • Boolean value
  • function
  • modular

I'll explain it in detail later

版权声明
本文为[Gao Yang, who would not be named]所创,转载请带上原文链接,感谢

  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