Casts of data types
If you want to convert one data type to another , Just put it into the corresponding type of function .
Number Data conversion of type
Cast to int
Data types that can be converted
- int integer
- float floating-point
- bool Boolean type
- str character string ( integer )
Data conversion
# integer ( Integer conversion is intact )
print(int(10))
# floating-point ( The floating-point type is converted into integer type according to the backward one method )
print(int(10.999))
# Boolean type ( Boolean has only two values , There are only two ways to convert to integers ,True=1,False=0)
print(int(True))
print(int(False))
# character string ( Strings can only be converted if they are integer without quotation marks )
print(int('-123'))
print(int('123'))
Cast to float
Data types that can be converted
- int integer
- float floating-point
- bool Boolean type
- str character string ( integer 、 floating-point )
Data conversion
# integer ( Integer conversion is to add a decimal , Would have a 0)
print(float(10))
# floating-point ( Floating point conversions are intact )
print(float(10.999))
# Boolean type ( Boolean has only two values , There are only two ways to convert to integers ,True=1.0,False=0.0)
print(float(True))
print(float(False))
# character string ( Strings can only be converted if they are integer and floating-point without quotation marks )
print(float('-123'))
print(float('1234.134'))
Cast to bool
Data types that can be converted
python All data types in can be converted to Boolean , But there are only two results ,True
and False
Data conversion
stay python in , There are only ten cases where data is converted into bool The value of is False, The rest are True.
# That is to say ,python All empty data in are False
# 1、 integer (0)
print(bool(0))
# 2、 floating-point (0.0)
print(bool(0.0))
# 3、 Boolean type (False)
print(bool(False))
# 4、 The plural (0j)
print(bool(0j))
# 5、 character string ( An empty string )
print(bool(''))
# 6、 list ( An empty list )
print(bool([]))
# 7、 Tuples ( An empty tuple )
print(bool(()))
# 8、 aggregate ( Empty set )
print(bool(set()))
# 9、 Dictionaries ( An empty dictionary )
print(bool({}))
# 10、None(python keyword , It means nothing )
print(bool(None))
Cast to complex
Data types that can be converted
- int integer
- float floating-point
- bool Boolean type
- complex The plural
- str character string ( integer 、 floating-point 、 The plural )
Data conversion
# integer ( Integer conversions are primitive numbers +0j)
print(complex(10))
# floating-point ( Floating point conversions are primitive numbers +0j)
print(complex(10.999))
# Boolean type ( Boolean has only two values , There are only two ways to convert to integers ,True=1+0j,False=0j)
print(complex(True))
print(complex(False))
# The plural ( The plural conversion is the same ,0+0j=0j)
print(complex(1234+341j))
print(complex(0+0j))
# character string ( A string is an integer only if the quotation marks are removed 、 Floating point and complex can be converted )
print(complex('-123'))
print(complex('1234.134'))
print(complex('1234+0j'))
Automatic conversion of number type
When different types of numbers work together , The result will be automatically converted from low to high accuracy . When a low precision number is operated on a high precision number , Finally, it will become a high precision number type
Sort from low to high precision :
bool -----> int -----> float ------> complex
- bool And besides bool The result of any data type operation other than is not bool
- complex Computing with any type of data becomes complex
# For example, low precision bool And high precision int Carry out operations , The result will be automatically transformed into high precision int
# bool + int
res = True + 100
print(res, type(res))
# bool + float
res = True + 100.11
print(res, type(res))
# bool + complex
res = True + 0j
print(res, type(res))
# int + float
res = 123 + 100.9
print(res, type(res))
# int + complex
res = 123 + 0j
print(res, type(res))
# float + complex
res = 100.0000 + 0j
print(res, type(res))
container Cast of type
Container type conversion , Use the function of the corresponding container for conversion .
Convert to string
Data types that support transformation
All data types
# Method 1、 Quote directly
print('[1, 2, 3]')
# Method 2、 Use str function
print(str([1, 2, 3]))
# [1, 2, 3]
# Method 3、 Use repr function
print(repr([1, 2, 3]))
# [1, 2, 3]
# repr Function function : Prototype the output string , Do not escape characters ( Show quotation marks )
lstvar = [1, 2, 3]
res = str(lstvar)
print(repr(res))
# '[1, 2, 3]'
Convert to list
Data types that support transformation
Only containers
Pay attention to the point
If it's a string , Will put each string as a separate element in the list ;
If it's a dictionary , Just keep the key , Form a new list ;
If it's another container , It's just a simple replacement on the basis of the original data [];
# 1、 character string
# Every character in a string is treated as an element
var = 'hello motherland'
print(list(var))
# ['h', 'e', 'l', 'l', 'o', ' ', 'm', 'o', 't', 'h', 'e', 'r', 'l', 'a', 'n', 'd']
# 2、 Dictionaries
var = {'one': 1, 'two': 2, 'three': 3}
print(list(var))
# ['one', 'two', 'three']
# 3、 Other data types
var = (1, 3, 4, 5, 6)
print(list(var))
# [1, 3, 4, 5, 6]
var = {1, 3, 4, 5, 6}
print(list(var))
# [1, 3, 4, 5, 6]
Convert to tuple
Data types that support transformation
Only containers
Pay attention to the point
If it's a string , Will put each string as a separate element in the list
If it's a dictionary , Just keep the key , Form a new list
If it's another container , It's just a simple replacement on the basis of the original data ()and list It's the same
# 1、 character string
# Every character in a string is treated as an element
var = 'hello motherland'
print(tuple(var))
# ('h', 'e', 'l', 'l', 'o', ' ', 'm', 'o', 't', 'h', 'e', 'r', 'l', 'a', 'n', 'd')
# 2、 Dictionaries
var = {'one': 1, 'two': 2, 'three': 3}
print(tuple(var))
# ('one', 'two', 'three')
# 3、 Other data types
var = [1, 3, 4, 5, 6]
print(tuple(var))
# (1, 3, 4, 5, 6)
var = {1, 3, 4, 5, 6}
print(tuple(var))
# (1, 3, 4, 5, 6)
Convert to set
Supported data types
Only containers
Pay attention to the point
Set changes and lists 、 Tuples are all the same , It's just a simple replacement on the basis of the original data {};
But the set is unordered , The order of elements in the returned result is not fixed
# 1、 character string
# Every character in a string is treated as an element
var = 'hello motherland'
print(set(var))
# {'d', 'r', ' ', 'h', 'n', 'e', 't', 'm', 'a', 'o', 'l'}
# 2、 Dictionaries
var = {'one': 1, 'two': 2, 'three': 3}
print(set(var))
# {'two', 'one', 'three'}
# 3、 Other data types
var = ['1', '3', '4', '5', '6']
print(set(var))
# {'5', '4', '6', '1', '3'}
var = ('1', '3', '4', '5', '6')
print(set(var))
# {'5', '4', '6', '1', '3'}
Multistage container
- Nesting a container within a container , This container is called a secondary container ; Nest another container among the nested containers , The outermost container is called a tertiary container ; And so on , There are four levels 、 Level five ……
- The type of container depends on the outermost container , Different types of containers can be nested within each other , however , Except for sets and dictionaries ; Because the key of the dictionary and the value in the collection must be of hashable type , Hashable data types Number、str、tuple;
- Multilevel containers don't include strings , Strings are special containers , Any character in a string is a separate element of the string ;
# Secondary container
# For example, nesting a list in a list
var = [1, 2, [1, 2, 3]]
# Three stage container
# For example, nesting a list in a list , There is also a tuple in the nested list
var = [1, 2, [3, 4, (5, 6)]]
# ……
# Secondary Dictionary
# Dictionaries use keys to store data , So the nested container should be placed under the key
var = {'1': 1, '2': 2, '666': {'3': 3, '4': 4}}
Get the value in the multilevel container
# Get the data in the nested container through subscript index 、 Key to get the data layer by layer
# practice : Get the value in the fourth level container !!! How to get 10
No1_level4_container = [1, 2, 3, 4, (1, 2, 3, 4, {1: 1, 2: 2, "msr": [1, 2, 3, 4, 10]})]
print("--- The original four stage container ")
print(No1_level4_container)
# In this multi-stage container , All the containers are the last , So the use of python Unique reverse subscript , Come and get it one by one
# 1、 Get tuples first . That's the second stage container
res = No1_level4_container[-1] # Release level one That is, through the subscript of the list -1 To choose
print("--- Release level one ")
print(res)
# 2、 In getting the dictionary
res = res[-1]
res1 = No1_level4_container[-1][-1]
print("--- Deprive level two ")
print(res)
print(res1)
# 3、 In getting the key value msr Corresponding value
res = res['msr']
print("--- obtain msr")
print(res)
# 4、 In getting the value 10 Subscript -1 perhaps 4
res1 = res[-1]
res2 = res[4]
print('--- final result ')
print(res1, res2)
# Abbreviation
res = No1_level4_container[-1][-1]['msr'][-1]
print('--- Abbreviate the results ')
print(res)
Multi stage containers of equal length
- The elements in the outer container are containers
- The number of elements in the nested container is the same
# A second stage container of equal length
var = [(1, 2, 3,), (4, 5, 6,)]
The strong conversion of Dictionary
requirement
It must be a secondary container of equal length , And the number of elements in it must be two .
Container conversion
# Use dict Function transformation
var = [('one', 1), ('two', 2)]
dctvar = dict(var)
print(dctvar)
print(type(dctvar))
# {'one': 1, 'two': 2}
# <class 'dict'>
Be careful
Recommended list 、 Tuples , Sets and strings are not recommended
# 1、 The outer layer is a list or tuple 、 aggregate , The recommended containers are tuples or lists
var = [(1, 2), [3, 4]]
res = dict(var)
print(res, type(res))
# 2、 Collection is not recommended
# If there's a collection inside , Grammatically, though , But there are limitations . Because the set is out of order , Often it doesn't fit the definition , That is to say, the first element in the secondary container may not be the key .
var = [{'1', 2}, {'2', 3}]
res = dict(var)
print(res)
# 3、 Strings are not recommended
# If you use strings , Grammatically correct , But there are limitations . Because a character in a string is treated as an element , So the length of a string cannot exceed two characters , Otherwise, it will not meet the requirements of forced transfer dictionary .
var = [[1, 2], "ab"]
print(dict(var))
var = [[1, 2], "abc"]
print(dict(var)) # error
The function of each data type
# Use it directly to create a null value of the same type , That is to say, it turns into Boolean false
print(int()) # 0
print(float()) # 0.0
print(bool()) # false
print(complex()) # 0j
print(str()) # ''
print(list()) # []
print(tuple()) # ()
print(set()) # set()
print(dict()) # {}