Python Basic Data Types for Python Introduction
1. Integer: int
For calculation, for comparison (the right side of the equals sign is executed first when assigning values)
The addition of 1.1 integers
a = 10 b = 20 print(a + b) //Result: 30
Subtraction of 1.2 integers
a = 10 b = 20 print(b - a) //Result 10
Multiplication of 1.3 Integers
a = 10 b = 20 print(a * b) //Result: 200
Division of 1.4 Integers
a = 10 b = 20 print(b / a) //Result: 2.0 # Note: When we use Python 3, we divide to get the floating-point number, which is decimal, but when we use Python 2, we divide to get the integer.
Integer divisions of 1.5 integers
a = 10 b = 20 print(b // a) //Result: 2
Remaining of 1.6 Integers
a = 5 b = 2 print(a % b) //Result: 1
Power of 1.7 Integers
a = 5 b = 2 print(a ** b) //Result: 25
(Python 3 divides by returning decimal (floating point) and Python 2 divides by returning integer (downward integer).
The range of int s on 32-bit machines is -231-231-1, i.e. -2147483648-2147483647.
The range of int s on 64-bit machines is -263-263-1, i.e. -9223372036854775808-9223372036854775807.
The difference between integers in Python 2 and Python 3:
Python 3: All integer
Python 2: Integer, long Integer
Conversion from 1.8 10 to 2
1.8.1 10 to 2: bin() function
Method: Divide 2 and write from bottom to top.
print(bin(30))
1.8.22 to 10: int("11011101", 2) function
Method: The current position of the number multiplied by 2 digits minus 1 power, and then add up.
print(int("111110",2))
2. Boolean value: bool
True-true false-false: (for judgment)
print(3 > 2) # Output borrowing result is True print(3 < 2) # The output is False
3. String: str
It is used to store some data and a small amount of data. In Python, as long as it is caused by quotation marks, it is a string. Every letter or character in a string is called an element (string stitching: string + string string doubling: string * number).
a = """absc""" print(a)
3.1 String Addition
#String splicing s1 = 'a' s2 = 'bc' print(s1 + s2)
3.2 String Multiplication (Multiplication Rule: Only String and Number Multiplication)
str*int name = 'Cockroach' print(name*8)
There is no subtraction or division in strings.
3.3 Index (subscript):
< 1 > from left to right row (forward index starts from 0)
< 2 > Row from right to left (Reverse index starts at - 1)
a = "hello_wiu_srr,_taa_ba_hello" print(a[5]) print(a[6]) print(a[11]) print(a[-2]) print(a[-1])
When indexing, you should not exceed the maximum value of the index.
3.4 sections:
[Initial position (including): termination position (excluding)]: regardless of the end
[Starting position:]: From default to final
[:]: Default from the beginning to the end
Slices can exceed index values
a = "hello_wiu_srr,_taa_ba_hello" print(a[21:100]) print(a[21:]) # [21 (starting position): (default to final)] print(a[:]) # [(Default starts from the beginning): (Default to the end)]
3.5 steps:
Step size determines the direction of the search, and the steps of the search
The default step size for slicing is 1
Positive index (from left to right) and negative index (from right to left)
In the end position: start position + step size to get the next character element
[:: -1]: Reverse output of strings
a = "hello_wiu_srr,_taa_ba_hello" print(a[1:8:2]) print(a[1:8:4]) print(a[-12:-3:2]) print(a[10:-5:1]) print(a[-5:-10:-1])
Strings are immutable data types and strings are ordered
3.6 String Method:
< 1 > upper (): all capitals
name = "maex" a = name.upper() # All capitals print(a) print(name)
<2> lower (): All lowercase
name = "MAEX" a = name.lower() # lowercase print(name) print(a)
<3> Starts with (): What to begin with
name = "maex" print(name.startswith('e',2,3)) # What to start with -- Boolean values are returned
<4> endswith (): What ends
name = "maex" print(name.endswith('l',0,2)) # What ends -- Boolean values are returned
< 5 > count (): statistics, counting
name = "maexwauisrtaaibbIa" print(name.count("i")) # Statistics, counting
<6> strip (): take off (space at both ends of the head and tail, newline \n, tab \t); remove the specified contents at both ends of the head and tail
pwd = " wslexsdsb " a = pwd.strip() # Delete by default (space at both ends of the head and tail, newline \n, tab \t) print(a) pwd = "alxasdsbala" a = pwd.strip("al") # Remove the contents specified at both ends of the head and tail print(a)
<7> split (): Splitting (default space, newline character\n, tab\t); can also be done with the specified element. You can specify the number of partitions
name = "allwex_wusu_sdi_r" a = name.split("_") # Partition (default space, newline charactern, tab character\t) print(a) print(name.split("_",2)) # You can specify the number of partitions
<8> Replace(): Replace. Replace("content to be replaced", "content to be replaced", number of replacements)
name = "alex,wusir,ta,i,b,a,i" a = name.replace(",",".") # replace all print(a) a = name.replace(",",".",4) # You can specify the number of substitutions print(a)
3.7 String Formatting:
format(): Fill in order of location; Fill in according to index; Fill in according to name
name = "{}This year:{}".format("Bao Yuan",18) # Fill in order of position print(name) name = "{1}This year:{0}".format("Bao Yuan",18) # Fill in by index print(name) name = "{name}This year:{age}".format(name="Bao Yuan",age=18) # Fill in by name print(name)
3.8 is series is judged to return Boolean values
(1) isdigit(): Determine whether the contents of the string are all numbers (Arabic numerals)
msg = "alex" print(msg.isdigit()) # Determine whether the contents of a string are all numbers (Arabic numerals)
(2) isdecimal(): Determine whether a decimal number is a decimal number
msg = "alex" print(msg.isdecimal()) # Judging whether decimal number or not
(3) isalnum(): Judging whether it is a number, letter, Chinese
msg = "alex" print(msg.isalnum()) # Judging whether it is a number, letter, Chinese
(4) Isalpha(): Judging whether it is a letter or not, Chinese
msg = "alex" print(msg.isalpha()) # Judging whether it is a letter or not, Chinese
3.9 str Data Type Method - Supplement:
< 1 > string name. capitalize(): capital letter
a = "alex Wusir" print(a.capitalize()) # title case
<2> string name. title(): capitalization of the initial letter of each word
a = "alex Wusir" print(a.title()) # Capital letters for each word
< 3 > string name. swapcase(): case-switching
a = "alex Wusir" print(a.swapcase()) # toggle case
<4> String Name. center(): Center Fill
a = "alex Wusir" print(a.center(20,"*")) # Centralization-Filling
<5> String name. find(): Find index by element, return - 1 if not found
a = "alex Wusir" print(a.find("c")) # Find index by element, return - 1 if not found
<6> String Name. index(): Find the index through the element and report an error if it cannot be found.
a = "alex Wusir" print(a.index("c")) # Find the index through the element, and report an error when it is not found
<7> "Elements for splicing". join(["1","2","3"]): splicing, converting lists into strings (ints cannot be spliced directly)
a = "alex Wusir" print(a.join("_")) lst = ["1","2","4"] print("_".join(lst)) # Stitching, converting lists into strings
<8>str + str
name1 = "al" name2 = "au" print(id(name1)) print(id(name2)) print(id(name1 + name2))
< 9 > STR * Number
name1 = "al" print(id(name1)) print(id(name1 * 5))
(String addition and multiplication open up new space)
4. List:list
Lists are one of the data types in Python, which can store a large number of different types of data. In other languages they are called arrays. The 32-bit Python limit is 536870912 elements, and the 64-bit Python limit is 11529221504606846975 elements. And the list is ordered, has index values, can be sliced, easy to get values.
4.1 Defines a list: lst = []
lst = [1,2,"alex",True,["Key","Entrance guard card",["Bank card"]]] print(lst)
List - Container
Lists are ordered containers that support indexing
List is a variable data type modified in situ
A comma-separated list is an element
Index of 4.2 Lists
Lists, like strings, have indexes:
lst = ['Lau Andy','Zhou Runfa','Jay Chou','Xianghuaqiang'] print(lst[0]) # The first element in the list print(lst[1]) # The second element in the list print(lst[2]) # The third element in the list
Note: Lists can be modified, unlike strings.
lst[3] = 'Wang Jianlin' print(lst)
String modification
s = 'Sephirex Wang' s[0] = 'plum' print(s) //Result: Traceback (most recent call last): File "D:/python_object/path2/test.py", line 1076, in <module> s[0] = 'plum' TypeError: 'str' object does not support item assignment
Slices of the 4.3 List
lst = ["Spatholobus tenuifolia", "Wang Jianling", "Ma Yun", "Dr. Zhou Hong", "Xianghuaqiang"] print(lst[0:3]) # ['Sparrow vine','Wang Jianqin','Ma Yun'] print(lst[:3]) # ['Sparrow vine','Wang Jianqin','Ma Yun'] print(lst[1::2]) # ['Wang Jianling','Dr. Zhou Hongyi'] also has strides. print(lst[2::-1]) # ['Ma Yun','Wang Jianqin','Ma Hua Teng'] can also be retrieved upside down. print(lst[-1:-3:-2]) # Reverse stride length
4.4 Increase in the list:
<1> append(): Add append at the end.
lst = [1,2,3,4,3] lst.append(13) # Add print(lst) at the end
<2> insert(): Inserting insert (insert location, insert content) to minimize the use of insert, will reduce efficiency
lst = [1,2,3,4,3] lst.insert(2,"ro") # insert print(lst)
<3> extend (): Iteratively add an add-on
lst = [1,2,3,4,3] lst.extend([1,2,3,4]) # Iterative addition (one by one) print(lst)
Delete the 4.5 list:
<1> remove (): Only one can be deleted, from left to right. Delete by element name
lst = [1,2,3,4,3] list.remove(1) print(lst)
<2> pop (): The pop-up deletes the last one by default, and has a return value, which is the pop-up one. You can also add subscripts to delete pop(3). Repr(): View the source ecosystem of the current data
lst = [1,2,3,4,3] print(repr(lst.pop(2))) # repr() Views the original ecology of the current data print(lst)
< 3 > clear (): empty
lst = [1,2,3,4,3] lst.clear() # empty print(lst)
<4> del(): Delete directly in memory space. Can be deleted by indexing, slicing, step size
lst = [1,2,3,4,3] del lst[4] # Delete by index del lst[2:5] # Delete by slicing del lst[1:5:2] # Delete by step size print(lst)
Amendments to the 4.6 List:
< 1 > LST [2] = 80: Modification by index
lst = [1,2,3,4,5] lst[2] = 80 # Modification by Index print(lst))
<2> Lst [1:3]= "skaj": Modification through slicing must be an iterative object. The default step size is 1, and the content can be changed more or less.
lst = [1,2,3,4,5] lst[1:3] = "20" # By slicing, the default step size is 1. The content of modification must be iteratable, and the content of modification can be more or less. print(lst)
<3> Lst [1:5:2]= "10": When the step size is not 1, it must be one-to-one.
lst = [1,2,3,4,5] lst[1:5:2] = 100,100 # When step size is not 1, print(lst) must be matched one by one.
4.7 List lookup:
< 1 > Search by Index
<2> for loop
lst = [1,2,3,4,5] for i in lst: print(i)
The nesting of 4.8 lists:
lst = [1,2,[3,4,5,["alex[]",True,[[1,2,]],90],"wusir"],"taibai"] lst1 = lst[2] # [3, 4, 5, ['alex[]', True, [[1, 2]], 90], 'wusir'] lst2 = lst1[3] # ['alex[]', True, [[1, 2]], 90] str_1 = lst2[0] print(str_1[-1]) print(lst[2][3][0][-1])
Layer by layer search, [... ] Think of it as an element
4.9 list Data Type Method - Supplement:
Definition of <1> List: list("123456")
The method of <2> list:
1 > List Name. index(): Find Index by Element
lst = [1,23,4,5,7,8,9] print(lst.index(4)) # Find index by element
2 > list name. reverse(): inversion
lst = [1,23,4,5,7,8,9] lst.reverse() print(lst)
3 > List Name. sort(): Sorting is ascending by default
lst = [1,23,4,5,7,8,9] lst.sort() # Sorting by default is ascending print(lst)
4 > List name. sort(reverse=True): descending order
lst = [1,23,4,5,7,8,9] lst.sort(reverse=True) # Descending order print(lst)
Questions:
lst = [1,[]] * 5 print(lst) # [1, [], 1, [], 1, [], 1, [], 1, []] lst[1].append(6) print(lst) # [1, [6], 1, [6], 1, [6], 1, [6], 1, [6]]
When a list is multiplied, the elements are shared
5. tuple
Tuples are one of the data types in Python. They are orderly, immutable, and only support queries. A tuple is an immutable list.
5.1 Definition: Tu = 1,2,3
tu = (1,2,"alex",[1,3,4]) print(tu)
Statistics of 5.2 tuples:
Tuple. count()
tu = (1,2,3,4,5,1,2,1) print(tu.count(1))
5.3 tuple access index:
Tuple. index(4): Query the index through elements
tu = (1,2,3,4,5,1,2,1) print(tu.index(2)) # Query index by element
Use of 5.4 tuples:
Use in configuration files
The nesting of 5.5 tuples:
tu = (1,2,3,4,(5,6,7,8,("alex","wusir",[1,23,4]))) print(tu[4][4][0])
(3)Tuple:
Questions:
tu = (1) \# tu1 = ("alex") \# tu2 = (1,) #tuple
5.6 tuple Data Type Method - Supplement:
<1> tu + tu
tu = (12,3,4) + (4,5,3,4) print(tu)
<2> tu*number
tu = (1,[]) * 3 print(tu) tu[-1].append(10) print(tu)
When a tuple is multiplied, the elements are shared
6. Dictionary - dict
Dictionary is one of the data structures in Python. It is an unordered and variable data type. All operations in dictionary are through keys.
6.1 Definition: dic = {"key": "value"} - Key-value pairs
6.2 The role of dictionaries:
Store a large amount of data and associate data with data
dic = {"10":"IPhone", "11":"IPhone", 15:"Mi phones", 15:"Huawei Mobile Phone", (1,):"oppo Mobile phone", } print(dic)
Key: Must be an immutable data type (hash), and unique
Value: Arbitrary, Variable (Not Hash)
6.3 Dictionary additions:
< 1 > Violence added:
dic ["key"]= "value"// dictionary addition, adding a key-value pair
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } dic["Sun Yang"] = "Xiao Ming" # The addition of a dictionary is a key-value pair. dic["Youngest sister"] = ["Listen to the music","Sing","eat","Baked Nang","Saute Spicy Chicken","Raisins"] print(dic)
<2> dic.setdefault ("key", ["value 1", [value 2"]// Yes, no, no:
First check if the key has a dictionary
Add when it doesn't exist
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } dic.setdefault("Yuanbao",["sing","jump","Basketball","drink"]) print(dic)
6.4 Delete the dictionary:
<1> pop(): //pop deletion is deleted by keys in the dictionary and returns deleted values.
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } print(dic.pop("Bao Yuan")) #The pop deletion returns the deleted value through the keyline deletion in the dictionary print(dic)
<2> clear (): //clearing
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } dic.clear() # empty print(dic)
<3> Deldic://Deletes the entire dictionary container
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } del dic # Delete the entire container. print(dic)
<4> del DIC ["keys"]: // Delete by keys
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } del dic["alex"] # Delete by key print(dic)
There is no remove in the dictionary
6.5 Dictionary modification:
<1> DIC ["key"]= "value": // overrides if there is one, and adds if not.
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } dic["alex"] = "dsb" # If yes, it will be covered and not added. print(dic)
<2> update (new dictionary): The dictionary level after the //update function is higher than that of the previous dictionary
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } dic1 = {"alex":"Having been to Peking University","wusir":"Have worked at the front end"} dic1.update(dic) print(dic1)
6.6 Dictionary Check:
<1> get ("key"): Return None get("key", "content specified by oneself") when the query is not available: Return the content specified by oneself when the query is not available
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } print(dic.get("alex")) # Inquiries do not return None print(dic.get("Yuanbao","I can't find it.")) # Return to your own content when you can't find it
<2> setDefault ("key"): Return None if // query is not available
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } print(dic.setdefault("alex")) # Inquiries do not return None
<3> DIC ["keys"]://Error reporting if query is not available
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } print(dic["alex"]) # Wrong report if not inquired
<4> dic.keys (): //View key gets a high imitation list
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } for i in dic: # View all keys print(i) print(dic.keys()) # What you get is a high imitation list.
<5> dic.values (): // View the value, get a high imitation list
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } for i in dic: # View all values print(dic.get(i)) print(dic.values()) # What you get is a high imitation list.
High imitation list supports iteration and index
for i in dic.values(): # High imitation list supports iteration print(i)
<6> items (): //View key-value pairs
dic = { "Sun devil":["Watch comic and animation","Bodybuilding","Eat steamed buns","Eat big pancakes","Eat big pancakes"], "Gunner":"aircraft", "Leopard brother":"Plaster", "Bao Yuan":"Sword", "alex":"Bragging" } for i in dic.items(): print(i[0],i[1])
6.7 Dictionary Nesting:
Dictionary nested lookup must be done layer by layer
dic = { 101:{1:{"Sun devil":"object"}, 2:{"Lao Wang next door":"Wang fried"}, 3:{"Jobiro":("Sun devil","Gunner","Bao Yuan")}, }, 102:{1:{"Wang Feng":{"International Chapter":["Small apple","Big Yali Pear"]}}, 2:{"Deng Ziqi":["foam","Faith","Lineage","Light years away"]}, 3:{"tengger":["Invisible Wings","Calorie","Sun Will Never Set"]} }, 103:{1:{"Cai Xukun":{"sing":["Chicken is too beautiful for you"], "jump":["Steel tube dance"], "rap":["Big Bowl Noodle Bar"], "Basketball":("NBA Image Ambassador")}}, 2:{"JJ":{"Walking CD":["Jiangnan","Cao Cao","Back-to-back hugs","Dimples","No tide, no money"]}}, 3:{"Jay":{"Jay":["Chrysanthemum Platform","Nunchaku","Huo Yuanjia"]}}}, 201:{ 1:{"Baby Way":{"Geminis":"Assassin","Jianning":{"princess":{"Wu Sangui":"The bear"}},"Lung er":{"Bishop's wife":"Hierarch"}}} } } print(dic[201][1]["Baby Way"]["Jianning"]["princess"]["Wu Sangui"]) print(dic[103][1]["Cai Xukun"]["jump"][0][1]) print(dic[102][2]["Deng Ziqi"][1])
6.8 dict Data Type Method - Supplement:
<1> Dictionary Name. popitem(): Random deletion, and returns the deleted key-value pair to delete the last key-value pair in Python 3.6
dic = {"key":1,"key1":2,"key2":4,"key3":1} print(dic.popitem()) # Random deletion python3.6 Edition deletes the last key-value pair # popitem returns deleted key-value pairs print(dic)
< 2 > dictionary name. fromkeys("a B c", []): batch creation of key-value pairs "a":[], "b":[], "c":[]
Questions:
dic = {} dic.fromkeys("abc",[]) # Create key-value pairs in batches print(dic)
The first parameter of fromkeys must be an iteratable object, which will be iterated as the key of the dictionary. The second parameter is the value (which is shared)
The value shared by fromkeys is that the variable data type will have pits, and the immutable data type will be okay.
dic = {} dic = dic.fromkeys("abc",[]) print(dic) dic["b"] = 11 dic["a"].append(10) print(dic)
7. Collection:
Collection is one of the data types in Python, which is disordered, variable and unique. Collection is a worthless dictionary, which is naturally de-duplicated.
Question: Reduplicate with one line of code
lst = [1,223,1,1,2,31,231,22,12,3,14,12,3] print(list(set(lst)))
7.1 Defines an empty set: set1 = set {}
7.2 Increase of set:
< 1 > collection name. add()
s = set() s.add("alex") print(s)
<2> Set name. update(): Iterative addition
s = set() s.update("wusir") # Iterative addition print(s)
7.3 The deletion of sets:
< 1 > Set name. remove(): Delete by element
s = {100,0.1,0.5,1,2,23,5,4} s.remove(4) # Delete by element print(s)
<2> Set Name. clear(): Clear
s = {100,0.1,0.5,1,2,23,5,4} s.clear() # empty print(s)
< 3 > Set name. pop(): Delete immediately (usually the smallest)
s = {100,0.1,0.5,1,2,23,5,4} s.pop() # Random deletion (usually the smallest) print(s)
7.4 Set Change:
Delete before add
s = {1,2,3,4,5} # Delete before add
7.5 Set Check:
for loop
Other operations of the 7.6 collection:
(1) difference set-
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s - s1) print(s1 - s)
(2) Intersection&
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s & s1)
(3) Unification|
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s | s1)
(4) Anti-intersection^
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s ^ s1)
(5) Subset <: Returns a Boolean value
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s < s1)
(6) Parent Set (Super)>:
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} print(s1 > s)
(7) frozen set
s = {1,23,9,4,5,7} s1 = {1,2,3,4,5} dic = {frozenset({1,23,4,5}):123} print(dic)