02. Python data types

Python entry data type##

The value of the variable stored in memory. This means that when a variable is created, a space is created in memory. Based on the data type of the variable, the interpreter allocates designated memory and decides what data can be stored in the memory. **** Therefore, variables can specify different data types, and these variables can store integers, decimals or characters.

1. Variable##

1.1 Variable assignment###

# Variable assignment in Python does not require type declarations.
# Each variable is created in the memory, including the identification, name and data of the variable.
# Each variable must be assigned a value before it is used, and the variable will be created after the variable is assigned.
# equal sign(=) Is used to assign values to variables.
# equal sign(=) The left side of the operator is a variable name,equal sign(=) The right side of the operator is the value stored in the variable. E.g:

conuter =100
miles =1000.0
name ="Json"print(conuter)print(miles)print(name)

1.2 Multiple variable assignment###

Python allows you to assign values to multiple variables, for example.

a = b = c =1print(a,b,c)

# You can also specify multiple variables for multiple objects,E.g:
a, b , c =1,2,"json"print(a,b,c)

**But in python, programmers don't need to care about memory overflow and other issues, because python has already helped implement memory management. **** 1. Reference counter **** 2. Garbage collection mechanism **** Each object maintains its own reference counter, and each time it is referenced, the counter will increase by 1. When the counter of an object is At zero hour, the garbage collection mechanism will clear him from the memory and release the memory space it previously occupied. **

Two, standard data type##

There can be many types of data stored in memory.
For example, a person’s age can be stored in numbers, and his name can be stored in characters.
Python defines some standard types for storing various types of data.
Python has five standard data types.

* Numbers
* String
* List
* Tuple (tuple)
* Dictionary

Three, Python number (Number)

Python numeric types are used to store numeric values. The numeric type is not allowed to be changed, which means that if the value of the numeric type is changed, the memory space will be reallocated

var1 =10  
var2 =20

You can also use the del statement to delete references to some digital objects.** The syntax of the del statement is:**

del var1[,var2[,var3[....,varN]]]  
  
# You can also delete references to single or multiple objects through the del statement, for example:  
del  var  
del  var_a,var_b  

Python supports three different numeric types

Integer (int): Usually referred to as an integer or an integer, it is a positive or negative integer without a decimal point. Python3 integer type has no size limit and can be used as Long type, so Python3 does not have Python2 Long type.

Floating point type (float): Floating point type is composed of integer part and decimal part. Floating point type can also be expressed in scientific notation (2.5e2 = 2.5 x 102 = 250)

Complex number (complex): A complex number consists of a real part and an imaginary part. It can be represented by a + bj, or complex (a, b). The real part a and imaginary part b of the complex number are both floating-point types.

We can also use hexadecimal and octal to represent integers:

>>> number =0xA0F #Hexadecimal
>>> number  
2575>>> number=0o37 #Octal
>>> number  
31
int float complex
10 0.0 3.14 j
100 15.20 45. j
- 786 - 21.9 9.322 e-36j
080 32.3 e+18 .876j
- 0490 - 90. - .6545+0 J
- 0 x260 -32.54e100 3e+26J
0 x69 70.2E-12 4.53e-7j

3.1 Python number type conversion

Sometimes, we need to convert the built-in data type, the data type conversion, only need to use the data type as the function name

* int(x)Convert x to an integer.
    
* float(x)Convert x to a floating point number.
    
* complex(x)Convert x to a complex number, the real part is x and the imaginary part is 0.
    
* complex(x, y)Convert x and y to a complex number, with the real part being x and the imaginary part being y. x and y are numeric expressions.
  
# The following example converts the floating-point variable a to an integer:  
a =1.0print(int(a))1

3.2 Python number operations

The Python interpreter can be used as a simple calculator. You can enter an expression in the interpreter and it will output the value of the expression. The syntax of the expression is very straightforward: +, -, * and /, Same as in other languages (such as Pascal or C). E.g:

>>>2+24>>>50- 5*620>>>(50- 5*6) /45.0>>>8/5  #Always return a floating point number
1.6

**Note: The results of floating-point operations on different machines may be different. **In integer division, division / always returns a floating-point number. If you only want to get the result of an integer, discard the possible fractional part, you can use arithmetic Symbol // :

>>>17 /3  #Integer division returns floating point
5.666666666666667>>>>>>17 // 3  #Integer division returns the result of rounding down 5>>>17%3  #The% operator returns the remainder of the division
2>>>5*3+217  
  
# note://The number obtained is not necessarily an integer type, it is related to the data type of the denominator numerator.  >>>7//2  3>>>7.0//2  3.0>>>7//2.0  3.0>>>

The equal sign = is used to assign values to variables. After assignment, the interpreter will not display any results except for the next prompt.

>>> width =20>>> height =5*9>>> width * height  
900

**Python can use operation for exponentiation

>>>5**2 # 5 squared
25>>>2**7 # 2 To the 7th power
128

Variables must be "defined" (that is, assign a value to the variable) before being used, otherwise an error will occur

>>> n   #Try to access an undefined variable
Traceback(most recent call last):  
 File "<stdin>", line 1,in<module>  
NameError: name 'n' is not defined  

When mixing different types of numbers, integers are converted to floating-point numbers

>>>3*3.75 /1.57.5>>>7.0/23.5

In interactive mode, the last output expression result is assigned to the variable _. E.g

>>> tax =12.5/100>>> price =100.50>>> price * tax  
12.5625>>> price + _  
113.0625>>> round(_,2)113.06  
# Here,_Variables should be treated as read-only variables by users

3.3 Random number function

**Random numbers can be used in the fields of mathematics, games, security, etc., and are often embedded in algorithms to improve algorithm efficiency and improve program security. **Python includes the following commonly used random number functions

Function Description
[ choice(seq)] Select an element randomly from the elements of the sequence, such as random.choice(range(10)), randomly select an integer from 0 to 9.
[ randrange ([start,] stop [,step])] Get a random number from the set that increases by the specified base within the specified range, the base default value is 1
[ random()] Generate the next real number randomly, which is in the range [0,1).
[ seed([x])] Change the seed of the random number generator. If you don't understand the principle, you don't need to set the seed specifically, Python will help you choose the seed.
[ shuffle(lst)] Randomly sort all elements of the sequence
[ uniform(x, y)] Generate the next real number randomly, which is in the range of [x,y].

Five, Python string##

String is the most commonly used data type in Python. We can use quotation marks ('or ``) to create a string. **** Creating a string is very simple, just assign a value to the variable, for example:

var1 ='Hello World!'  var2 ="Runoob"

5.1 Python accesses the value in a string

A string or string (String) is a string of characters composed of numbers, letters, and underscores.
Generally marked as

s="a1a2···an"(n>=0)

# It is the data type that represents text in a programming language
# Python string has 2 value order:
# The index from left to right starts at 0 by default, and the maximum range is string length 1.
# Right to left index default-Starting at 1, the maximum range is the beginning of the string

If you want to obtain a substring from a string, you can use [head subscript: tail subscript] to intercept the corresponding string, where the subscript starts from 0 and can be a positive or negative number. The label can be empty to indicate the beginning or the end.

[ Head subscript: tail subscript] The obtained substring contains the characters of the head subscript but not the characters of the tail subscript.
such as:

s ='youmen'print(s[1:5])

When using a colon-separated string, python returns a new object, and the result contains the continuous content identified by the pair of offsets, and the beginning on the left contains the lower boundary.

The above result contains the value b of s[1], and the maximum range taken does not include the tail subscript, which is the value f of s[5].

str ='Hello Wrold'print(str)print(str[0])print(str[2:5])print(str[2:])print(str *2)print(str +"TEST")

Hello Wrold
H
llo
llo Wrold
Hello WroldHello Wrold
Hello WroldTEST

5.2 Python string update

You can intercept a part of the string and splice it with other fields, as in the following example:

var1 ='hello world'print(var1[:6]+'Runnob!')

# The output of the above example is
hello Runnob!

5.3 Python escape character

When you need to use special characters in a character, Python uses a backslash () to escape the character. The following table:

Escape character description
( At the end of a line) line continuation character
| Backslash symbol
' Single quote
" Double quotes
\ a Bell
\ b Backspace
\000 Empty
\ n newline
\ v Vertical tab
\ t Horizontal tab character
\ r Enter
\ f page change
\ oyy octal number, the character represented by yy, for example: \o12 represents line feed, where o is a letter, not the number 0.
\ xyy Hexadecimal number, the character represented by yy, for example: \x0a represents newline
\ other Other characters are output in normal format

5.4 Python string operator###

In the following table, the value of variable a is'hello' and variable b is'Python

Operator description example
+ String concatenation a + b Output result: HelloPython
* Repeated output string a*2 Output result: HelloHello
[] Get the characters in the string by index a[1] Output result e
[ : ] To intercept a part of the string, follow the principle of left closed and right open, str[0,2] does not contain the third character. a[1:4] Output result ell
in member operator-if the string contains the given character, it returns True 'H' in a and outputs the result True
not in member operator-if the string does not contain the given character, it returns True 'M' not in a and outputs the result True
% format string see below

5.5 Python string formatting

**Python supports the output of formatted strings. Although very complicated expressions may be used in this way, the most basic usage is to insert a value into a string with the string format character %s. **
**In Python, string formatting uses the same syntax as the sprintf function in C.

Example

print('My name is%s this year%d years old!'%('Xiao Ming',10))
My name is Xiaoming, 10 years old!

Python string formatting symbols

Symbol Description
%c Formatting characters and their ASCII codes
%s format string
%d formatted integer
%u Format unsigned integer
%o Format unsigned octal number
%x Format unsigned hexadecimal number
%X Format unsigned hexadecimal number (uppercase)
%f Format floating-point numbers, you can specify the precision after the decimal point
%e Format floating point numbers in scientific notation
%E Same function as %e, format floating point numbers in scientific notation
Shorthand for %g %f and %e
Shorthand for %G %f and %E
%p Format the address of the variable with a hexadecimal number

Python triple quotes
**Python triple quotation marks allow a string to span multiple lines. The string contains line breaks, tabs, and other symbols, as follows:

para_str ="""This is an example of a multi-line string
Multi-line strings can use tabs
TAB(\t).
You can also use line breaks[\n]."""
print(para_str)

# The output of the above example is
This is an example of a multi-line string
Multi-line strings can use tabs
TAB().
You can also use line breaks[].
# Triple quotation marks free programmers from the quagmire of quotation marks and special characters,Maintaining the format of a small string from beginning to end is the so-called WYSIWYG format.
# A typical use case is,When you need a piece of HTML or SQL, use string combination at this time, special string escape will be very cumbersome.

5.6 f-string

f-string was added after python3.6. It is called a literal format string and is a new format string syntax. We used to use percent signs (%) before:

>>> name ='Runoob'>>>'Hello %s'% name  
' Hello Runoob'
# f-The string format and the string start with f, followed by the string, and the expressions in the string use braces{}wrap up,
# He will replace the calculated value of the variable or expression,Examples are as follows.

name ='Runoob'print(f'Hello {name}')

age =20print(f'{age+1}')

w ={'name':'Runoob','url':'www.runoob.com'}print(f'{w["name"]}:{w["url"]}')

Hello Runoob
21
Runoob:www.runoob.com

**In Python2, ordinary strings are stored as 8-bit ASCII codes, while Unicode strings are stored as 16-bit unicode strings, which can represent more character sets. The syntax used is to prefix the string with u. **In Python3, all strings are Unicode strings

5.7 Python's string built-in functions###

Python's string commonly used built-in functions are as follows:

Serial number Method and description
1 capitalize() converts the first character of the string to uppercase
2 center(width, fillchar) returns a string with the specified width in the center, fillchar is the filled character, and the default is a space.
3 count(str, beg= 0,end=len(string)) returns the number of occurrences of str in string, if beg or end is specified, returns the number of occurrences of str in the specified range
4 bytes.decode(encoding="utf-8", errors="strict") There is no decode method in Python3, but we can use the decode() method of the bytes object to decode a given bytes object. This bytes object can be generated by str. encode() to encode the return.
5 encode(encoding='UTF-8',errors='strict') encodes the string in the encoding format specified by encoding, if an error occurs, a ValueError exception will be reported by default, unless errors specify'ignore' or'replace'
6 endswith(suffix, beg=0, end=len(string)) Check whether the string ends with obj, if beg or end is specified, check whether the specified range ends with obj, if yes, return True, otherwise return False
7 expandtabs(tabsize=8) converts the tab symbols in the string to spaces. The default number of spaces for tab symbols is 8.
8 find(str, beg=0, end=len(string)) detects whether str is contained in the string, if the range beg and end are specified, then check whether it is contained within the specified range, if it contains, return the starting index value, otherwise return -1
9 index(str, beg=0, end=len(string)) is the same as find(), except that if str is not in the string, an exception will be reported.
10 isalnum() returns True if the string has at least one character and all characters are letters or numbers, otherwise it returns False
11 isalpha() returns True if the string has at least one character and all characters are letters, otherwise it returns False
12 isdigit() returns True if the string contains only digits, otherwise returns False..
13 islower() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, it returns True, otherwise it returns False
14 isnumeric() If the string contains only numeric characters, it returns True, otherwise it returns False
15 isspace() If the string contains only blanks, it returns True, otherwise it returns False.
16 istitle() returns True if the string is titled (see title()), otherwise it returns False
17 isupper() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, it returns True, otherwise it returns False
18 join(seq) uses the specified string as the delimiter to combine all the elements (the string representation) in seq into a new string
19 len(string) returns the length of the string
20 ljust(width[, fillchar]) returns a new string with the original string left-justified and filled to the length width with fillchar. The fillchar defaults to a space.
21 lower() converts all uppercase characters in the string to lowercase.
22 lstrip() cuts off the spaces or specified characters on the left side of the string.
23 maketrans() creates a conversion table of character mapping. For the simplest call method that accepts two parameters, the first parameter is a string, which indicates the character to be converted, and the second parameter is also a string that indicates the target of the conversion.
24 max(str) returns the largest letter in the string str.
25 min(str) returns the smallest letter in the string str.
26 replace(old, new [, max]) replaces str1 in the string with str2. If max is specified, the replacement will not exceed max times.
27 rfind(str, beg=0,end=len(string)) is similar to the find() function, but searches from the right.
28 rindex( str, beg=0, end=len(string)) is similar to index(), but starts from the right.
29 rjust(width,[, fillchar]) returns a new string with the original string right-justified and filled to the length width with fillchar (default space)
30 rstrip() removes the spaces at the end of the string.
31 split(str="", num=string.count(str))num=string.count(str)) Use str as the separator to intercept the string, if num has a specified value, only num+1 substrings are intercepted
32 splitlines([keepends]) is separated by lines ('\r','\r\n', \n') and returns a list containing each line as an element. If the parameter keepends is False, no line breaks are included. If it is True , The newline character is retained.
33 startswith(substr, beg=0,end=len(string)) checks whether the string starts with the specified substring substr, if yes, it returns True, otherwise it returns False. If beg and end specify values, check within the specified range.
34 strip([chars]) performs lstrip() and rstrip() on the string
35 swapcase() converts uppercase to lowercase and lowercase to uppercase in a string
36 title() returns a "titled" string, which means that all words start with uppercase and the remaining letters are lowercase (see istitle())
37 translate(table, deletechars="") according to the table given by str (containing 256 characters) to convert the characters of the string, the characters to be filtered out are placed in the deletechars parameter
38 upper() converts lowercase letters in a string to uppercase
39 zfill (width) returns a string of length width, the original string is right aligned, and the front is filled with 0
40 isdecimal() checks whether the string contains only decimal characters, and returns true if it is, otherwise it returns false.

Six, Python list##

List (list) is the most frequently used data type in Python.
The list can complete the data structure realization of most collections. It supports characters, numbers, strings and even lists (ie nesting).
The list is marked with [], which is the most common compound data type in python.

The cutting of the value in the list can also use the variable [head subscript: tail subscript] to intercept the corresponding list. The index from left to right starts at 0 by default, and the index from right to left starts at -1 by default. Empty means to get to the beginning or end.

In addition, Python has built-in methods for determining the length of the sequence and determining the largest and smallest elements.
The list is the most commonly used Python data type, and it can appear as a comma separated value in square brackets.
The data items of the list need not have the same type
To create a list, simply enclose the different data items separated by commas in square brackets. As follows:

list1 =['Google','Runoob',1997,2000]
list2 =[1,2,3,4,5]
list3 =["a","b","c","d"]
# note:The following examples all use the variables here as templates

Like the index of the string, the index of the list starts from 0, and the list can be intercepted, combined, etc.

6.1 Access the value in the list

Use the subscript index to access the values in the list, and you can also use square brackets to intercept characters, as shown below:

print("list1[0]", list1[0])print("list2[1:3]",list2[1:3])

# The output of the above example is:
list1[0] Google
list2[1:3][2,3]

6.2 update list###

print('The first element of list1 is:',list1[1])
list1[1]='youmen'print('The elements of list1 are:',list1[1])

# The output of the above example is:
The first element of list1 is: Runoob
The elements of list1 are: youmen

# You can also use append()method

6.3 Delete list element###

You can use the del statement to delete the elements of the list, as shown in the following example

list3 =["a","b","c","d"]print("Original list list3",list3)
del list3[0]print("Delete the 0th element",list3)

# The output of the above example is
Original list list3['a','b','c','d']
Delete the 0th element['b','c','d']

# Of course, you can also use remove()Method delete

6.4 Python list script operator###

**The operators of the list pairs + and * are similar to strings. The + sign is used for combined lists, and the * sign is used for repeated lists. **

Python expression Result Description
len([1, 2, 3]) 3 length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Combination
[' Hi!'] * 4 ['Hi!','Hi!','Hi!','Hi!'] Repeat
3 in [1, 2, 3] True Does the element exist in the list
for x in [1, 2, 3]: print(x, end=" ") 1 2 3 Iteration

6.5 Interception and splicing of Python lists and nested lists###

Python's list interception and string manipulation types are as follows

L =['Google','Runoob','Taobao']print(L[2])print(L[-2])print(L[1:])

str1 =[1,4,9,13]
str1 +=[15,18,20,22]print(str1)

# The output of the above example is
Taobao
Runoob
[' Runoob','Taobao'][1,4,9,13,15,18,20,22]

Nested list

stra =['a','b','c']
strb =['d','e','f']
strc =[stra,strb]print(strc)print(strc[0])print(strc[0][1])

# The output of the above example is:[['a','b','c'],['d','e','f']]['a','b','c']
b

6.6 Python list functions & methods###

Python contains the following functions:

Serial number function
1 len(list) Number of list elements
2 max(list) returns the maximum value of list elements
3 min(list) returns the minimum value of list elements
4 list(seq) convert a tuple to a list

Python contains the following methods

Serial number Method
1 list.append(obj) adds a new object at the end of the list
2 list.count(obj) count the number of times an element appears in the list
3 list.extend(seq) appends multiple values in another sequence at the end of the list (extend the original list with the new list)
4 list.index(obj) Find the index position of the first match of a value from the list
5 list.insert(index, obj) insert object into list
6 list.pop([index=-1]) removes an element from the list (the last element by default), and returns the value of the element
7 list.remove(obj) removes the first match of a value in the list
8 list.reverse() Reverse the elements in the list
9 list.sort( key=None, reverse=False) Sort the original list
10 list.clear() Clear the list
11 list.copy() Copy list

The plus sign + is the list concatenation operator, and the asterisk * is the repeated operation, as shown in the following example:

list =['runoob',788,3.14,'youmen',77]
youmen =['flying']print(list)print(list[0])print(list[2:4])print(list[2:])print(list *2)print(list + youmen)

# The output of the above example:['runoob',788,3.14,'youmen',77]
runoob
[3.14,' youmen'][3.14,'youmen',77]['runoob',788,3.14,'youmen',77,'runoob',788,3.14,'youmen',77]['runoob',788,3.14,'youmen',77,'flying']

6.7 Use the list as a stack

The list method makes the list easy to use as a stack. The stack is used as a specific data structure. The element that enters first is released last (last in, first out). Use the append() method to add an element to the top of the stack. You can release an element from the top of the stack by using the pop() method without specifying an index. E.g:

Example

>>> stack =[3,4,5]>>> stack.append(6)>>> stack.append(7)>>> stack   
[3,4,5,6,7]>>> stack.pop()7>>> stack   
[3,4,5,6]>>> stack.pop()6>>> stack.pop()5>>> stack   
[3,4]

6.8 Use the list as a queue

You can also use the list as a queue, but the first element added in the queue is taken out first; but using the list for this purpose is not efficient. Adding or popping elements at the end of the list is fast, but inserting or popping from the head of the list is not fast (because all other elements have to move one by one).
Example3

from collections import deque >> queue = deque(["Eric", "John", "Michael"]) >> queue.append("Terry") # Terry arrives >> queue.append("Graham") # Graham arrives >> queue.popleft() # The first to arrive now leaves 'Eric' >> queue.popleft() # The second to arrive now leaves 'John' >> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])

6.9 List comprehension###

List comprehensions provide an easy way to create lists from sequences. Usually the application program applies some operations to each element of a certain sequence, and uses the result obtained as the element to generate a new list, or creates a sub-sequence according to certain judgment conditions.

Each list comprehension is followed by an expression for for, and then there are zero or more for or if clauses. The return result is a list generated from the subsequent for and if contexts based on the expression. If you want the expression to deduce a tuple, you must use parentheses.

Here we multiply each value in the list by three to obtain a new list:

Example

>>> vec =[2,4,6]>>>[3*x for x in vec][6,12,18]  
  
# We can also perform power calculations on him:>>>[[x, x**2]for x in vec][[2,4],[4,16],[6,36]]  
  
# You can call a method one by one for each element in the same sequence before:>>> freshfruit =['  banana','  loganberry ','passion fruit  ']>>>[weapon.strip()for weapon in freshfruit]['banana','loganberry','passion fruit']  
  
# We can also use if clauses as filters:>>>[3*x for x in vec if x >3][12,18]>>>[3*x for x in vec if x <2][]  
  
# Here are some demos on loops and other tricks:>>> vec1 =[2,4,6]>>> vec2 =[4,3,-9]>>>[x*y for x in vec1 for y in vec2][8,6,-18,16,12,-36,24,18,-54]>>>[x+y for x in vec1 for y in vec2][6,5,-7,8,7,-5,10,9,-3]>>>[vec1[i]*vec2[i]for i inrange(len(vec1))][8,12,-54]  
  
# List comprehensions can use complex expressions or nested functions:>>>[str(round(355/113, i))for i inrange(1,6)]['3.1','3.14','3.142','3.1416','3.14159']

6.10 Nested list comprehension###

Python lists can also be nested
The following example shows a 3X4 matrix list

Example5

>>> matrix =[...[1,2,3,4],...[5,6,7,8],...[9,10,11,12],...]  
  
# The following example converts a 3X4 matrix list into a 4X3 list
>>>[[ row[i]for row in matrix]for i inrange(4)][[1,5,9],[2,6,10],[3,7,11],[4,8,12]]  
  
# The following examples can also be implemented using the following methods:>>> transposed =[]>>>for i inrange(4):...     transposed.append([row[i]for row in matrix])...>>> transposed   
[[1,5,9],[2,6,10],[3,7,11],[4,8,12]]

Seven, Python3 tuple##

Tuple is another data type, similar to List (list)
Tuples are identified by (), and internal elements are separated by commas, but the tuple cannot be assigned twice, which is equivalent to a read-only list
Tuples are not allowed to be updated, while lists are allowed to update. The creation of tuples is very simple, just add elements in parentheses and separate them with commas

tup1 =(50)print(type(tup1))
tup2 =(50,)print(type(tup2))<class'int'><class'tuple'>
# Tuples are similar to strings. The subscript index starts from 0 and can be intercepted, combined, etc..

7.1 Access tuple###

Tuples can use the subscript index to access the values in the tuple, as in the following example

tuple =('runoob',788,3.14,'youmen',77)
youmen =(123,'flying')print(tuple)print(tuple[0])print(tuple[2:4])print(tuple[2:])print(tuple *2)print(tuple + youmen)

# The output of the above example('runoob',788,3.14,'youmen',77)runoob(3.14,'youmen')(3.14,'youmen',77)('runoob',788,3.14,'youmen',77,'runoob',788,3.14,'youmen',77)('runoob',788,3.14,'youmen',77,123,'flying')

7.2 Modify Tuple###

The element value in the tuple is not allowed to be modified, but we can connect and combine the tuple, as shown in the following example

tup1 =(1,2,3)
tup2 =('flying','youmen')
tup3 = tup1 + tup2
print(tup3)(1,2,3,'flying','youmen')

7.3 Delete tuple###

The elements in the tuple are not allowed to be deleted, but we can use the del statement to delete the entire tuple, as shown in the following example

tup =('Google','Runoob',1999,2000)print(tup)
del tup
print("The deleted tuple tup:")print(tup)('Google','Runoob',1999,2000)
The deleted tuple tup:Traceback(most recent call last):
 File "c:\Users\You-Men\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", 

# After the above instance tuple is deleted, the output variable will have abnormal information, the output is as follows:

The deleted tuple tup:Traceback(most recent call last):
 File "test.py", line 8,in<module>print(tup)
NameError: name 'tup' is not defined

7.4 Tuple Operator###

Like character strings, you can use + and * to perform operations between tuples. This means that they can be combined and copied, and a new tuple will be generated after the operation

Python expression Result Description
len((1, 2, 3)) 3 Calculate the number of elements
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Connect
(' Hi!',) * 4 ('Hi!','Hi!','Hi!','Hi!') Copy
3 in (1, 2, 3) True Does the element exist
for x in (1, 2, 3): print (x,) 1 2 3 Iteration

7.5 Tuple index, interception###

**Because a tuple is also a sequence, we can access the element at the specified position in the tuple, and we can also intercept a segment of the element in the index, as shown below: Tuple: **

tup =('Google','Runoob',1999,2000)print(tup[2])print(tup[-2])print(tup[1:])

# The output of the above example
19991999(' Runoob',1999,2000)
Python expression Result Description
L[2] 'Runoob' Read the third element
L[-2] 'Taobao' Reverse reading; reading the second-to-last element
L[1:] ('Taobao','Runoob') Intercept the elements, all elements after the second.

7.6 Tuple built-in functions###

The Python3 tuple contains the following built-in functions

Serial number Method and description Example
1 len(tuple) calculates the number of tuple elements tuple1 = ('Google','Runoob'); len(tuple1);2
2 max(tuple) returns the maximum value of the element in the tuple. tuple2=('5','4','3') ;max(tuple2); 5
3 min(tuple) returns the minimum value of the elements in the tuple tuple3 = ('5','4','8');min(tuple3);4
4 tuple(seq) list1=[1,2,3]; tuple4=tuple(list1);tuple4

Regarding the immutable tuples** The so-called immutable tuples refer to the different address values in the memory pointed to by the tuples.**

>>> tup =('r','u','n','o','o','b')>>> tup[0]='g'     #Does not support modifying elements
Traceback(most recent call last):  
 File "<stdin>", line 1,in<module>  
TypeError:'tuple' object does not support item assignment  
>>> id(tup)     #View memory address
4440687904>>> tup =(1,2,3)>>>id(tup)4441088800    #The memory address is different

Immutability is not a bad thing. For example, when we pass data to an API that we don’t understand, we can ensure that our data will not be modified. Similarly, if we manipulate a tuple returned from a function, we can convert it into a list through the built-in List() function.

Eight, Python dictionary##

Dictionary is another variable container model, and can store any type of object
Each key value (key=> value) pair of the dictionary is separated by a colon (:), and each pair is separated by a comma (,). The entire dictionary is enclosed in curly braces ({}), the format is as follows:
Dictionary (dictionary) is the most flexible built-in data structure type in Python besides lists. A list is an ordered collection of objects, and a dictionary is an unordered collection of objects.

The difference between the two is that the elements in the dictionary are accessed through keys, not offsets.

8.1 Access the value in the dictionary

The dictionary is identified by "{ }". The dictionary consists of an index (key) and its corresponding value.

# Example1
youmen ={'name':'tom','code':6379,'youmen':'flying'}print(youmen['name'])print(youmen['code'])

tom
6379

# Example2

dict ={'Alice':'1234','youmen':'22','Cecil':'3258'}print("dict[Alice]",dict['Alice'])print('dict[youmen]',dict['youmen'])

dict[Alice]1234
dict[youmen]22

8.2 Modify dictionary###

The way to add new content to the dictionary is to add new key/value pairs, modify or delete existing key/value pairs as follows:

dict ={'Alice':'1234','youmen':'22','Cecil':'3258'}
dict['Alice']=1
dict['youmen']=22print(dict['Alice'])print(dict['youmen'])

# The following is the output result of the example
122

8.3 Delete dictionary element

**A single element can be deleted and the dictionary can also be cleared. Only one operation is required to clear a dictionary. ****Display delete a dictionary with the del command, as in the following example:

dict ={'Alice':'1234','youmen':'22','Cecil':'3258'}
del dict['Alice']
dict.clear()
del dict
print(dict['Alice'])

# At this time, running the above instance will report an error and raise an exception, because the dictionary no longer exists after the del operation is executed:

8.4 The characteristics of dictionary keys###

**The dictionary value can be any python object, either a standard object or a user-defined one, but the key does not work. ****Two important points need to be remembered: **1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:

dict ={'Alice':'1234','youmen':'22','Cecil':'3258','Alice':'Little rookie'}print("dict['Alice']:",dict['Alice'])

# The output of the above example is
Little rookie

2 ) The key must be immutable, so it can be used as a number, string or tuple, but not a list, as in the following example:

dict ={[Alice]:'1234','youmen':'22','Cecil':'3258','Alice':'Little rookie'}

# The output of the above example:Traceback(most recent call last):
 File "test.py", line 3,in<module>
 dict ={['Name']:'Runoob','Age':7}
TypeError: unhashable type:'list'

8.5 Dictionary built-in functions & methods###

Python includes the following built-in functions:

Serial number function and description example
1 len(dict) Counts the number of dictionary elements, that is, the total number of keys. >>> dict = {'Name':'Runoob','Age': 7,'Class':'First'} >>> len(dict) 3
2 str(dict) Output dictionary, expressed as a printable string. >>> dict = {'Name':'Runoob','Age': 7,'Class':'First'} >>> str(dict) "{'Name':'Runoob','Class': 'First','Age': 7}"
3 type(variable) returns the input variable type, if the variable is a dictionary, it returns the dictionary type. >>> dict = {'Name':'Runoob','Age': 7,'Class':'First'} >>> type(dict)<class 'dict'>

The Python dictionary contains the following built-in methods:

Serial number function and description
1 radiansdict.clear() delete all elements in the dictionary
2 radiansdict.copy() returns a shallow copy of a dictionary
3 radiansdict.fromkeys() creates a new dictionary, uses the elements in the sequence seq as the keys of the dictionary, and val is the initial value corresponding to all the keys of the dictionary
4 radiansdict.get(key, default=None) returns the value of the specified key, if the value is not in the dictionary, it returns the default value
5 key in dict If the key is in the dictionary dict, return true, otherwise return false
6 radiansdict.items() returns a traversable (key, value) tuple array as a list
7 radiansdict.keys() returns an iterator, which can be converted to a list using list()
8 radiansdict.setdefault(key, default=None) is similar to get(), but if the key does not exist in the dictionary, the key will be added and the value will be set to default
9 radiansdict.update(dict2) Update the key/value pairs of dictionary dict2 to dict
10 radiansdict.values() returns an iterator, which can be converted to a list using list()
11 pop(key[,default]) Delete the value corresponding to the given key of the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, the default value is returned.
12 popitem() randomly returns and deletes the last pair of keys and values in the dictionary.

Nine, Python3 collection##

**A set is an unordered sequence of non-repeating elements. ****You can use braces {} or set() to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary. **Create format:

parame ={value01,value02,...}
or
set(value)

basket ={'apple','orange','apple','pear','orange','banana'}print(basket)print('apple'in basket)

# The output of the above example is
{' apple','banana','orange','pear'}
True

# The following shows the operation between two sets
a =set('admin')
b =set('youmen')print(a - b)print(a ^ b)print(a | b)print(a & b)

# The following is the output result of the example
{' i','d','a'}		#Set a contains elements not contained in b
{' u','d','i','y','a','e','o'}{'a','u','e','o','n','m','i','d','y'}  #Elements contained in both a and b
{' n','m'}		#Elements contained in both a and b.

9.1 Add element###

Add element x to collection a

thisset =set(('admin','Google','Taobao'))
thisset.add('youmen')print(thisset)
thisset.update('flying')print(thisset)

# The output of the above example
{' Taobao','Google','youmen','admin'}{'admin','n','Taobao','y','f','Google','l','youmen','g','i'}

9.2 Remove element###

Move the element x out of the set a, if it does not exist, an error will be reported

thisset =set(('admin','Google','Taobao'))
thisset.remove("Taobao")print(thisset)

# The output of the above example
{' admin','Google'}

9.3 Count the number of collection elements and clear the collection###

# Count the number of collection elements
thisset =set(('admin','Google','Taobao'))print(len(thisset))3

# Empty collection
thisset.clear()print(thisset)set()

# Determine whether the element exists in the collection
x  in thisset
thisset =set(('admin','Google','Taobao'))print('admin'in thisset)

True


Collections also support comprehensions

>>> a ={x for x in'YouMen'if x not in'o'}>>> a   
{' e','u','Y','n','M'}

9.4 Complete list of built-in methods###

Method Description
add() Add elements to the collection
clear() Remove all elements in the collection
copy() Copy a collection
difference() Returns the difference of multiple sets
difference_update() Remove the element in the set, which also exists in the specified set.
discard() Delete the specified element in the collection
intersection() Returns the intersection of sets
intersection_update() Returns the intersection of sets.
isdisjoint() Judging whether the two sets contain the same element, if not, return True, otherwise return False.
issubset() Judging whether the specified set is a subset of the method parameter set.
issuperset() Determine whether the parameter set of this method is a subset of the specified set
pop() Randomly remove elements
remove() Remove the specified element
symmetric_difference() Returns a collection of elements that are not repeated in the two collections.
symmetric_difference_update() Remove the same elements in another specified set in the current set, and insert different elements in another specified set into the current set.
union() Returns the union of two sets
update() Add elements to the collection

Ten, traversal skills##

When traversing in the dictionary, keywords and corresponding values can be interpreted simultaneously using the items() method:

>>> dict ={'nginx':80,'tomcat':8080,'Mysql':3306}>>>for i,k in dict.items():...print(i,k)...   
nginx 80   
tomcat 8080   
Mysql 3306   
    
# Enumerate can be used to traverse the sequence()function
>>> for i ,v inenumerate(['tic','tac','toe']):...print(i,v)...0 tic   
1 tac   
2 toe   
    
# If you want to traverse a sequence in reverse, first specify the sequence, and then call reversed()function:>>>for i inreversed(range(1,10,2)):...print(i)...97531   
    
# Traverse a sequence in order, use sorted()The function returns a sorted sequence without modifying the original value:>>> dict ={'nginx':80,'tomcat':8080,'Mysql':3306,'Redis':6379,'NTP':123}>>> dict   
{' nginx':80,'tomcat':8080,'Mysql':3306,'Redis':6379,'NTP':123}>>>for i insorted(set(dict)):...print(i)...   
Mysql   
NTP   
Redis   
nginx   
tomcat   

Eleven, Python data type conversion##

Sometimes, we need to convert the built-in type of the data, the conversion of the data type, you only need to use the data type as the function name.

The following built-in functions can perform conversion between data types. These functions return a new object that represents the converted value.

col1 col2
Function Description
[ int(x [,base])] Convert x to an integer
[ long(x [,base] )] Convert x to a long integer
[ float(x)] Convert x to a floating point number
[ complex(real [,imag])] Create a complex number
[ str(x)] Convert object x to string
[ repr(x)] Convert object x to expression string
[ eval(str)] Used to calculate valid Python expressions in a string and return an object
[ tuple(s)] Convert the sequence s into a tuple
[ list(s) Convert the sequence s into a list
[ set(s)] Convert to variable set
[ dict(d) Create a dictionary. d must be a sequence (key, value) tuple.
[ frozenset(s)] Convert to immutable set
[ chr(x)] Convert an integer to a character
[ unichr(x)] Convert an integer to a Unicode character
[ ord(x)] Convert a character to its integer value
[ hex(x) Convert an integer to a hexadecimal string
[ oct(x)] Convert an integer to an octal string

Twelve, memory management##

* Variables do not need to be declared in advance, and do not need to specify the type
	*Characteristics of dynamic languages

* Generally, there is no need to care about the survival of variables or the management of memory in programming.
* Python uses reference counting to record the number of references to all variables.(Reference counter, garbage collection mechanism)*When the variable reference count becomes 0, it can be garbage collected GC
	*Count increase:Assign to other variables to increase the reference count, such as x=3,y=x
	*Count decrease:*When the function runs, local variables will be automatically destroyed, and the object reference count will decrease
		*Variables are assigned to other objects, such as x=3;y=x;x=4*Regarding performance issues, you need to consider the issue of variable references, but to release the memory, try not to release the memory, depending on the demand.

Recommended Posts

02. Python data types
Python basic data types
Python basic data types
Python learning-variable types
Python data model
Python data analysis
python data structure
Python data format-CSV
Python data analysis-apply function
Python data analysis-data selection
Python data analysis-data establishment
Detailed explanation of data types based on Python
Python Data Science: Neural Networks
Python common data structure collation
Python Data Science: Logistic Regression
Python data structure and algorithm
Python Data Science: Regularization Methods
Python Data Science: Related Analysis
Python Data Science: Linear Regression
Python Faker data forgery module
Python Data Science: Chi-Square Test
Python Data Science: Linear Regression Diagnosis
Detailed explanation of python sequence types
Python realizes online microblog data visualization
Is python suitable for data mining
Python basic syntax and number types
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
Automatically generate data analysis report with Python
Python access to npy format data examples
Python basics
Python descriptor
Python basics 2
Python exec
Python3 tuple
Python decorator
Python IO
Python multithreading
Python toolchain
Comprehensive summary of Python built-in exception types
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
Can variable types be declared in python
07. Python3 functions
Python basics 3
Java or Python for big data analysis
Python multitasking-threads
Python uses pandas to process Excel data
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string