Objectives:
1. List
2. Tuple
3. Dictionary
4. String
5. Public method
6. Advanced variable
In python, all non numeric variables have the following characteristics:
① Is a sequence, which can also be understood as a container
② Value []
③ Traverse for in
④ Calculation length, Max / min value, comparison, deletion
⑤ Connect + and repeat*
⑥ Slice
1, List
·List is the most frequently used data type in python and is often called array in other languages
·Designed to store a string of information
·The list is defined by [], and the data is separated by ","
·The index of the list starts from 0 (index is the position number of data in the list, which can also be called subscript)
For example: name_list = [“zhangsan”,“lisi”,“wangwu”]
1. List method
name_list = ["zhangsan", "lisi", "wangwu"] # 1. Value and index # List index out of range - list index out of range print(name_list[0]) # Know the content of the data and want to determine the position of the data in the list # When using the index method, it should be noted that if the transmitted data is not in the list, the program will report an error! print(name_list.index("wangwu")) # 2. Modification name_list[1] = "Li Si" # list assigment index out of range # The index specified in the list is out of range. The program will report an error! # name_list[3] = "Wang Xiaoer" # 3. Increase # The append method appends data to the end of the list name_list.append("Wang Xiaoer") # The insert method can insert data at the specified index position of the list name_list.insert(1, "Li Xiaodan") # The extend method can append the complete contents of other lists to the end of the current list temp_list = ["Sun WuKong", "Zhu Bajie", "Sha Shidi"] name_list.extend(temp_list) # 4. Delete # The remove method deletes the specified data from the list name_list.remove("wangwu") # The pop method can delete the last element in the list by default name_list.pop() # The pop method specifies the index of the element to be deleted name_list.pop(3) # The clear method clears the list name_list.clear() print(name_list)
2. Understand del keyword
name_list = ["Zhang San", "Li Si", "Wang Wu"] # (yes) use the delete keyword (delete) to delete list elements # Tip: in daily development, to delete data from the list, it is recommended to use the method provided by the list # The del keyword is essentially used to delete a variable from memory # Note: if you use the del keyword to delete a variable from memory # Subsequent code can no longer use this variable del name_list[1] print(name_list)
3. List statistics
name_list = ["Zhang San", "Li Si", "Wang Wu", "Wang Xiaoer", "Zhang San"] print(name_list) # The length (length) function counts the total number of elements in the list list_len = len(name_list) print("List contains %d Elements" % list_len) # The count method can count the number of occurrences of a data in the list count = name_list.count("Zhang San") print("Zhang San appeared %d second" % count) # Delete data from the list (first occurrence of data) name_list.remove("Zhang San") print(name_list)
4. List sorting
name_list = ["zhangsan", "lisi", "wangwu", "wangxiaoer"] num_list = [2, 5, 3, 8, 5] # Ascending order name_list.sort() num_list.sort() # Descending order name_list.sort(reverse=True) num_list.sort(reverse=True) # Reverse order (reverse) name_list.reverse() num_list.reverse() print(name_list) print(num_list)
5. Iterative traversal
·In python, you can use the for loop to iterate over all non numeric variables: lists, tuples, dictionaries, and strings.
name_list = ["Zhang San", "Li Si", "Wang Wu", "Wang Xiaoer"] # Use iterations to get data sequentially from the list """ Get data from the list in sequence. In each cycle, the data will be saved in the my_name In this variable, The data obtained this time can be accessed in the temporal part of the circulatory body for Variables used inside the loop in list: for my_name in name_list: The loop operates on list elements internally print(my_name) """ for my_name in name_list: print("My name is %s" % my_name)
6. List application scenarios
·Although different types of data can be stored in python's list
·However, in development, more application scenarios are:
① Lists store the same type of data
② Through iterative traversal, the same operation is performed for each element in the list within the loop.
2, Tuple
·Tuple s are similar to lists, except that the elements of tuples cannot be modified
. Tuples represent a sequence of elements
. Tuples have specific application scenarios in python development
·It is used to store a string of information, and the data are separated by ","
·Tuples are defined with ()
·The index of tuples starts at 0
. An index is the position number of data in a tuple
1. Definition of tuples
① Create an empty tuple (generally not used)
info_tuple = ()
② When a tuple contains only one element, you need to add a comma after the element
info_tuple = (5,)
③ Define tuple
info_tuple = ("zhangsan", 15, 5, 23)
2. Common operations of tuples
info_tuple = ("zhangsan", 13, 1.75, "zhangsan") # 1. Value and index # Value - tuple name [] print(info_tuple[0]) # Fetch index - tuple name. index("content") # You already know the content of the data and want to know the index of the data in the tuple print(info_tuple.index("zhangsan")) # 2. Statistical counting print(info_tuple.count("zhangsan")) # Count the number of elements contained in the tuple print(len(info_tuple))
3. Loop traversal
·In python, you can use the for loop to iterate over all non numeric variables: lists, tuples, dictionaries, and strings.
·Tip: in actual development, unless the data type in tuples can be confirmed, there is not much need for cyclic traversal of tuples.
info_tuple = ("zhangsan", 45, 1.35) # Use iteration to traverse tuples for my_info in info_tuple: # Use format strings to splice my_info this variable is inconvenient # Because the data types stored in tuples are usually different print(my_info)
4. Application scenario
·Although you can use for in to traverse tuples.
·However, in development, more application scenarios are:
. Function parameters and return values. A function can receive any number of parameters or return multiple data at a time.
. Format string. The () after the format string is essentially a tuple.
. Make the list non modifiable to protect data security.
info_tuple = ("Xiao Ming", 21, 1.34) # The () after the format string is essentially a tuple print("%s Age is %d Height is %.2f" % info_tuple)
5. Conversion between tuples and lists
·Use the list function to convert tuples into lists
list(tuple)
·Use the tuple function to convert a list into tuples
tuple((list)
3, Dictionary
·Dictionaries are the most flexible data types in python besides lists
·Dictionaries can also be used to store multiple data
. It is usually used to store relevant information used to describe an object
·Difference between and list
. A list is an ordered collection of objects
. A dictionary is an ordered collection of objects
·Dictionaries are defined with {}
xiaoming = {"name":"Xiao Ming","age":18,"gender":True,"height":1.75}
·Dictionaries use key value pairs to store data, and key value pairs are separated by ","
The key is the index key
The data value value is
Use between keys and values:
. The key must be unique
. Values can be any data type, but keys can only use strings, numbers, or tuples
1. Common operations of adding, deleting, modifying and looking up dictionaries
xiaoming_dic = {"name": "Xiao Ming"} # 1. Value print(xiaoming_dic["name"]) # If the specified key does not exist during value taking, the program will report an error # print(xiaoming_dic["name123"]) # 2. Add / modify # If the key does not exist, a key value pair will be added xiaoming_dic["age"] = 18 # If the key exists, the existing key value pair will be modified xiaoming_dic["name"] = "Xiao Ming" # 3. Delete xiaoming_dic.pop("name") # When deleting the specified key value pair, if the specified key does not exist, the program will report an error! # xiaoming_dic.pop("name123") print(xiaoming_dic)
2. Statistics, merging and clearing of dictionaries
xiaoming_dic = {"name": "Xiao Ming", "age": 18} # 1. Count the number of key value pairs print(len(xiaoming_dic)) # 2. Merge dictionary temp_dic = {"height": 75, "age": 20} # Note: if the merged dictionary contains existing key value pairs, the original key value pairs will be overwritten xiaoming_dic.update(temp_dic) # 3. Empty dictionary xiaoming_dic.clear() print(xiaoming_dic)
3. Circular traversal of dictionary
xiaoming_dic = {"name": "Xiao Ming", "qq": 254225, "phone": 10086} # Iterative traversal dictionary # Variable k is the key value pair key obtained in each cycle for k in xiaoming_dic: print("%s - %s" %(k, xiaoming_dic[k])
4. Application scenario of dictionary and list combination
·Although you can use for in to traverse the dictionary
·However, in development, more application scenarios are:
. Use multiple key value pairs to store relevant information describing an object -- more complex data information
. Put multiple dictionaries in a list, then traverse, and do the same processing for each dictionary within the loop body
# Use multiple key value pairs to store relevant information describing an object -- more complex data information # Put multiple dictionaries in a list, then traverse, and do the same processing for each dictionary within the loop body card_list = [ {"name": "Zhang San", "qq": 12345, "phone": 110}, {"name": "Li Si", "qq": 54321, "phone": 10086 } ] for card_info in card_list: print(card_info)
4, String
·A string is a string of characters. It is a data type representing text in a programming language
·In python, you can use a pair of double quotes or a pair of single quotes to define a string
. In actual development, most programming languages use "to define strings. If you need to use" internally, you can use "to define strings"
·You can use the index to get the character at the specified position in a string, and the index count starts from 0
·You can also use the for loop to iterate through each character in the string
str1 = "hello python" str2 = 'My nickname is "coconut"' print(str2) print(str1[2]) # Traversal of string for c in str2: print(c)
1. Common operations of string
·len (string) -- gets the length of the string
·String. Count (string) -- the number of times a small string appears in a large string
·String [index] - extract a single character from a string
·String. Index (string) -- gets the index of the first occurrence of a small string
hello_str = "hello hello" # 1. Statistics string length print(len(hello_str)) # 2. Count the number of occurrences of a small (sub) string print(hello_str.count("llo")) # If there is no in the program, no error will be reported print(hello_str.count("abc")) # 3. Where a substring appears print(hello_str.index("llo")) # Note: if the substring passed by the index method does not exist, the program will report an error # print(hello_str.index("abc"))
2. Judgment type (9)
·isspace() can also determine \ t \ n \ R
# 1. Judge white space characters space_str = " \t\n\r" print(space_str.isspace()) # 2. Determines whether the string contains only numbers # 1> Can't judge decimals # num_str = "1.1" # 2> Nuicode string # num_str = "\u00b2" # 3> Chinese numbers num_str = "Coconut" print(num_str) print(num_str.isdecimal()) print(num_str.isdigit()) print(num_str.isnumeric())
3. Find and replace
hello_str = "hello world" # 1. Determines whether to start with the specified string print(hello_str.startswith("hello")) # 2. Determines whether to end with the specified string print(hello_str.endswith("world")) # 3. Find the specified string # The index method can also find the index of the specified string in a large string print(hello_str.find("llo")) # The index method will report an error if the specified string does not exist # find returns - 1 if the specified string does not exist print(hello_str.find("abc")) # 4. Replace string # When the replace method is completed, a new string is returned # Note: the contents of the original string will not be modified print(hello_str.replace("world", "python")) print(hello_str)
4. Text alignment
# Requirements: output the following contents in order and centered poem = ["Climb the stork tower", "wang zhihuan", "The day is at the end of the mountain", "The Yellow River flows into the sea", "in order to see far away", "Take it to the next level"] for poem_str in poem: # Center alignment # print("|%s|" % poem_str.center(10, " ")) # Align left # print("|%s|" % poem_str.ljust(10, " ")) # Align right print("|%s|" % poem_str.rjust(10, " "))
5. Remove white space characters
# Requirements: output the following contents in order and centered poem = ["\t\n Climb the stork tower", "wang zhihuan", "The day is at the end of the mountain\t\n", "The Yellow River flows into the sea", "in order to see far away", "Take it to the next level"] # First, use the strip method to remove white space characters from the string # Then use the center method to center the text print("|%s|" % poem_str.strip().center(10, " "))
6. Split and connect
7. Slicing of strings
·The slicing method applies to strings, lists, tuples
Slicing uses index values to limit the range, cutting out small strings from a large string
Lists and tuples are ordered collections, and the corresponding data can be obtained through the index value
A data dictionary is an unordered collection that uses key value pairs to store data
5, Public method
List, tuple, dictionary and string can all be used.
1. python built-in functions
·Note:
. string comparisons comply with the following rules: "0" < "a" < "a"
The dictionary cannot compare sizes
. del can be used in two ways:
a. Keyword del a[1]
b. Function del(a[1])
2. Slice
3. Operator
·Attention
When operating on a dictionary, in judges the key of the dictionary
The operators in and not in are called member operators
The results extend and qppend can also be spliced, except that they are not output directly
t_list = [1,2] t_list.extend([3,4]) print(t_list)
Output: [1,2,3,4]
t_list = [1,2,3,4] t_list.append([8,9]) print(t_list)
Output: [1,2,3,4, [8,9]]
4. Complete for loop syntax
for num in [1, 2, 3]: print(num) if num == 2: break else: # If break is used inside the loop body to exit the loop # The code below else will not be executed print("Will it be implemented?") print("End of cycle")
6, Advanced variable