Mandatory conversion of Python data type

osc_ 25qqqijt 2021-01-23 12:57:18
mandatory conversion python data type


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
  1. int integer
  2. float floating-point
  3. bool Boolean type
  4. 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
  1. int integer
  2. float floating-point
  3. bool Boolean type
  4. 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
  1. int integer
  2. float floating-point
  3. bool Boolean type
  4. complex The plural
  5. 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

  1. bool And besides bool The result of any data type operation other than is not bool
  2. 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

  1. 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 ……
  2. 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;
  3. 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
  1. The elements in the outer container are containers
  2. 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()) # {}
版权声明
本文为[osc_ 25qqqijt]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/01/20210123125537397A.html

  1. Mandatory conversion of Python data type
  2. Django reported an error: 'key' ID 'not found in' xxx '. Choices are: xxx'
  3. Python 400 sets of large video, starting from the right direction to learn, a complete set to you
  4. 只需十四步:从零开始掌握Python机器学习(附资源)
  5. Just 14 steps: Master Python machine learning from scratch (resources attached)
  6. Python|文件读写
  7. 安利一个Python界神奇得网站
  8. Python | file reading and writing
  9. Amway is a marvelous website in Python world
  10. 第二热门语言:从入门到精通,Python数据科学简洁教程
  11. The second popular language: from introduction to mastery, python data science concise tutorial
  12. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  13. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  14. 以我的亲身经历,聊聊学python的流程,同时推荐学python的书
  15. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  16. Django url 路由匹配过程
  17. Django URL routing matching process
  18. 强者一出,谁与争锋?与Python相比,C++的运行速度究竟有多快?
  19. Who will fight against the strong? How fast is C + + running compared with Python?
  20. python 学习体会
  21. Experience of learning Python
  22. python7、8章
  23. Chapter 7 and 8 of Python
  24. python bool和str转换
  25. python——循环(for循环、while循环)及练习
  26. python变量和常量命名、注释规范
  27. python自定义异常捕获异常处理异常
  28. python 类型转换与数值操作
  29. python 元组(tuple)和列表(list)区别
  30. 解决python tkinter 与 sleep 延迟问题
  31. python字符串截取操作
  32. Python bool and STR conversion
  33. Python -- loop (for loop, while loop) and Practice
  34. Specification for naming and annotating variables and constants in Python
  35. Python custom exception capture exception handling exception
  36. Python type conversion and numerical operation
  37. The difference between tuple and list in Python
  38. Solve the delay problem of Python Tkinter and sleep
  39. Python string interception operation
  40. Python 100天速成中文教程,GitHub标星7700
  41. Python 100 day quick Chinese course, GitHub standard star 7700
  42. 以我的親身經歷,聊聊學python的流程,同時推薦學python的書
  43. With my own experience, I'd like to talk about the process of learning Python and recommend books for learning python
  44. python爬虫获取起点中文网人气排行Top100(快速入门,新手必备!)
  45. Python crawler to get the starting point of Chinese network popularity ranking Top100 (quick start, novice necessary!)
  46. 【Python常用包】itertools
  47. Itertools
  48. (国内首发)最新python初学者上手练习
  49. (国内首发)最新python初学者上手练习
  50. (first in China) the latest practice for beginners of Python
  51. (first in China) the latest practice for beginners of Python
  52. (数据科学学习手札104)Python+Dash快速web应用开发——回调交互篇(上)
  53. (data science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  54. (数据科学学习手札104)Python+Dash快速web应用开发——回调交互篇(上)
  55. (data science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  56. (資料科學學習手札104)Python+Dash快速web應用開發——回撥互動篇(上)
  57. (materials science learning notes 104) Python + dash rapid web application development -- callback interaction (Part 1)
  58. Python OpenCV 图片高斯模糊
  59. Python OpenCV image Gaussian blur
  60. Stargan V2: converse image synthesis for multiple domains reading notes and Python code analysis