Python learning notes 2: basic data types

Su Xiaodi eating brown rice cake 2020-11-13 16:50:48
python learning notes basic data


Python Variables in do not need to be declared . Each variable must be assigned a value before use , The variable will not be created until it is assigned a value .
stay Python in , Variable is variable , It has no type , What we say " type " Is the type of object in memory that the variable refers to .
Equal sign (=) Used to assign values to variables .
Equal sign (=) To the left of the operator is a variable name , Equal sign (=) To the right of the operator is the value stored in the variable .

Python There are six standard data types in :

data type Definition variability
Number( Numbers ) int, bool, float, complex,long(python2) Immutable data
String( character string ) Single quotation marks ' Or double quotes " Cover up , Use the backslash at the same time \ Escapes special characters Immutable data
List( list ) In square brackets [] Between 、 Comma separated list of elements Variable data type
Tuple( Tuples ) Write it in parentheses () in , The elements are separated by commas Immutable data
Set( aggregate ) Use braces { } perhaps set() Function to create a collection Variable data type
Dictionary( Dictionaries ) A dictionary is a mapping type , Dictionary use { } identification , It's a disorder key (key) : value (value) Set Variable data type

Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary ;
For dictionaries : key (key) Immutable type must be used . In the same dictionary , key (key) Must be unique .

Number( Numbers )
Python The number types of are int integer 、long Long integer (python2)、float Floating point numbers 、complex The plural 、 And Boolean (0 and 1).
You can use the built-in type() Function can be used to query the object type of variable , You can also use isinstance To judge the type :

var_int=123
print(type(var_int))
var_float=1.01
print(type(var_float))
var_bool=True
print(type(var_bool))
var_complex=1+2j
print(type(var_complex))
print(isinstance(var_int, int))
print(isinstance(var_float, float))

The output is as follows :

<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
True
True

isinstance and type The difference is that :
type() A subclass is not considered a superclass type .
isinstance() Think of a subclass as a superclass type .

Be careful :
1、 stay Python2 There is no Boolean in , It uses numbers 0 Express False, use 1 Express True. To Python3 in , hold True and False Defined as a keyword , But their value is still 1 and 0, They can be added to numbers .
2、Python Multiple variables can be assigned at the same time , Such as a, b = 1, 2.
3、 A variable can be assigned to different types of objects .
4、 The division of a number consists of two operators :/ Returns a floating point number ,// Returns an integer .
5、 In mixed calculation ,Python Will convert integer to floating point .

String( character string )
Python Use single quotes for strings in ' Or double quotes " Cover up , Use the backslash at the same time \ Escapes special characters . You can also prefix a string with r, It means that string escape is forbidden .
Strings are immutable . All about characters we can start with Indexes 、 section 、 length 、 Traverse 、 Delete 、 Division 、 Clear the blanks 、 toggle case 、 Judge what to start with and so on .
Create string

# String form : Use ‘’ perhaps “” To create a string
var_str1='temp_string1'
print(var_str1)
var_str2="temp_string2"
print(var_str2)

1) Indexes / section
Strings can also be intercepted ( retrieval ). Be similar to C , The first character index of the string is 0 .Python No separate character type ; A character is a simple length of 1 String .
The index can also be negative , This will result in counting from the right . Except index , It also supports slicing . The index is used to get a single character , Slicing lets you get a substring .
as follows , The first line of numbers gives the index point in the string 0…6. The second line gives the corresponding negative index . Slicing is from i To j All characters between two numerical boundaries .

 +---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

The index can also be negative , This will result in counting from the right .

>>> var_str='temp_string'
>>> var_str[1]
'e'
>>> var_str[-1]
'g'
>>> var_str[0:-2] # From the first to the last , It doesn't include the second from the bottom
'temp_stri'

Be careful , Contains the starting character , Does not contain the last character . This makes s[:i] + s[i:] Always equal to s.
Sliced indexes have very useful default values ; The first index omitted defaults to zero , The omitted second index defaults to the size of the sliced string .

>>> var_str='temp_string'
>>> var_str[2:]
'mp_string'
>>> var_str[:2]
'te'
>>>

2) length
Built in functions len() Return string length :

>>> s='thisisatestlongstring'
>>> len(s)
21

3) Delete

>>> s='python'
>>> del(s)

4) toggle case

>>> s='this is a string'
>>> print(s.capitalize())
This is a string
>>> print(s.title())
This Is A String

List( list )
The list is written in square brackets [] Between 、 Comma separated list of elements .
List can complete the data structure implementation of most collection classes . The types of elements in a list can vary , It supports Numbers , Strings can even contain lists ( The so-called nested ).
Just like a string , The list can also be indexed and intercepted , After the list is truncated, a new list containing the required elements is returned .
Each value in the list has a corresponding position value , Call it an index , The first index is 0, The second index is 1, And so on .-1 To start at the end .

>>> list=['abcd', 123, 4.56, "python", 789]
>>> print(list)
['abcd', 123, 4.56, 'python', 789]
>>> print(list[0])
abcd
>>> print(list[1:3])
[123, 4.56]
>>> print(list[2:])
[4.56, 'python', 789]
>>> print(list[:-1])
['abcd', 123, 4.56, 'python']

What's different from a string is , The elements in the list can be changed :

>>> list=['abcd', 123, 4.56, "python", 789]
>>> print(list[2])
4.56
>>> list[2]=100.1 # Update the third element in the list
>>> print(list)
['abcd', 123, 100.1, 'python', 789]
>>> del list[1] # Delete the second element in the list
>>> print(list)
['abcd', 100.1, 'python', 789]

Unlike string truncation , List interception can receive the third parameter , The parameter function is the step size of interception . If the third parameter is negative, it means reverse reading .
The following examples are in the index 1 To the index 8 And set the step size to 2( One place apart ) To intercept words

>>> list=[1,2,3,4,5,6,7,8,9,0]
>>> print(list[1:8:2])
[2, 4, 6, 8]
>>> print(list[-3:-10:-2]) # Reverse interception , From the third to the last element to the tenth from the bottom , The reverse intercept step is 2
[8, 6, 4, 2]

You can also use nested lists, which create other lists in the list :

>>> list=[1, ['a','b'], 2]
>>> print(list[1])
['a', 'b']
>>> print(list[1][1])
b

Tuple( Tuples )
Tuples (tuple) Like a list , The difference is that the elements of a tuple cannot be modified .
Tuples are written in parentheses () in , The elements are separated by commas . The element types in tuples can also be different .
Tuples are similar to strings , Can be indexed and subscript indexed from 0 Start ,-1 For the position starting from the end .
When a tuple contains only one element , You need to add a comma after the element , Otherwise parentheses will be used as operators :

>>> tup=(50)
>>> type(tup)
<class 'int'>
>>> tup1=(50,) # An element , Comma needs to be added after element
>>> type(tup1)
<class 'tuple'>

Set( aggregate )
aggregate (set) Is an unordered sequence of non-repeating elements .
You can use braces { } perhaps set() Function to create a collection .
Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary .

Create format :

>>> s={1, 2, 3}
>>> print(s)
{1, 2, 3}
>>> s=set((1, 2, 3))
>>> print(s)
{1, 2, 3}

Dictionary( Dictionaries )
Dictionary is another variable container model , And can store any type of object .
Each key value of the dictionary key=>value Yes, with a colon : Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :

d = {key1 : value1, key2 : value2, key3 : value3 }

A list is an ordered collection of objects , A dictionary is an unordered collection of objects . The difference between the two is : The elements in the dictionary are accessed by keys , Instead of accessing by offset .
key (key) Immutable type must be used .
In the same dictionary , key (key) Must be unique .

>>> dict1={}
>>> dict1['name']='Python'
>>> dict1['age']=18
>>> print(dict1)
{'name': 'Python', 'age': 18}
>>> dict2={'name':'python', 'age':18}
>>> print(dict2)
{'name': 'python', 'age': 18}
>>> print(dict2.keys())
dict_keys(['name', 'age'])
>>> print(dict2.values())
dict_values(['python', 18])
>>> dict3=dict([('name', 'python'), ('age', 1)]) #(key, value) Tuple sequences create dictionaries
>>> print(dict3)
{'name': 'python', 'age': 1}
>>> dict4=dict(name='python', age=18) # Keywords create dictionaries
>>> print(dict4)
{'name': 'python', 'age': 18}

Delete dictionary elements , Can delete a single element can also empty the dictionary :

>>> dict={'name': 'python', 'age': 18}
>>> del dict['age']
>>> print(dict)
{'name': 'python'}
>>> dict.clear()
>>> print(dict)
{}
>>> del dict

Dictionary values can be anything python object , It can be a standard object , It can also be user-defined , But the key doesn't work .

Two important points to remember :
1) The same key is not allowed to appear twice . When creating, if the same key is assigned twice , The latter value will be remembered , The following example :

>>> dict={'name': 'python', 'age': 18, 'name':'lily'}
>>> print(dict)
{'name': 'lily', 'age': 18}

2) The key must be immutable , So you can use numbers , A string or tuple acts as , Not with lists , The following example :

>>> dict={['name']: 'python', 'age': 18}
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
dict={['name']: 'python', 'age': 18}
TypeError: unhashable type: 'list'
版权声明
本文为[Su Xiaodi eating brown rice cake]所创,转载请带上原文链接,感谢

  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