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 ([email protected]) 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
-
「 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 toS[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 -
「 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 fromX[I]
Start , ToX[J]
end , But not includingX[J]
-
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]: [1, 2, 'egg', 4, 5, 6]
# Lists also support repeating operations
In [26]: L*2
Out[26]: [1, 2, 'egg', 1, 2, '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]: [1, 2, 3, 4]
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]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [36]: diag=[M[i][i] for i in [0,1,2]]
In [37]: diag
Out[37]: [1, 5, 9]
# The legendary list generation
In [38]: L = [[x,x/2,x*2] for x in range(-6,7,2) if x>0]
In [39]: L
Out[39]: [[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]]
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]: (1, 2, 3, 4, 5, 6)
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]: {1, 2, 3, 4}
In [89]: Y
Out[89]: {3, 4, 5, 6}
# intersection
In [90]: X&Y
Out[90]: {3, 4}
# Combine
In [91]: X|Y
Out[91]: {1, 2, 3, 4, 5, 6}
# Difference set
In [92]: X-Y
Out[92]: {1, 2}
# 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