list
List Introduction (Master)
A list is like a box. Put the names of the students in the class in the box.
List is one of the most basic and commonly used data structures in Python. It is an ordered and repeatable collection of elements and a sequence. From the perspective of data structure, Python's list is a variable length sequential storage structure, and each location stores pointers to objects. It is defined with [], and the elements in the are separated with ","
We can modify, slice, append, delete, nest, iterate and judge members of the list.
List creation (Master)
To create a list, just enclose the different data elements separated by commas in square brackets.
In addition, we can also create a list directly through list()
# Method 1: create an empty list with a square bracket in English li_1 = [] print(type(li_1)) # --> <class 'list'> li_2 = ["clara", 21, 20.5, True, 21] # -->Elements can be of any type and can be repeated print(type(li_2),li_2) # --><class 'list'> ['clara', 21, 20.5, True, 21] #Mode 2: list() print(list()) # -->[] empty list # list(iterable) # -->Iterative means that elements can be taken out one by one print(list("hello")) # --> ['h', 'e', 'l', 'l', 'o'] print(list(1234567)) # -->An error is reported. An integer is not a sequence type. It is stored as a whole and is not iterative. print(list("1234567")) # --> ['1', '2', '3', '4', '5', '6', '7']
be careful:
- It is better not to use list for variable names
- The elements in the list can be of any type
- iterable represents an iteratable object. In short, it can be taken out element by element. For example: str
Access (look up) elements in the list (Master)
The query method is the same as the string. The subscript starts from 0 by default. If it exceeds the index range, an error will be reported.
The list starts at 0 and creates a subscript index for each of its elements in order until the total length is reduced by one. To access one of its elements, use square brackets and subscript values.
Pay attention to ensure that the index does not exceed the range. Once the accessed index exceeds the range, an exception will be thrown. So, be sure to remember that the index of the last element is len(list)-1.
reflection:
How does li = [1,2] extract elements? print(li[0]),print(li[1])
Modify the elements in the list (Master)
Directly take out the element for re assignment
reflection:
li = ['a', 'b', 'c'] how to change 'a' to 'a'.
The list is a variable sequence. Take a from the list and assign a to li[0].
li = list('abc') # --> ['a', 'b', 'c'] li[0] = 'A' print(li) # --> ['A', 'b', 'c']
Delete the elements in the list (Master)
Take out the element directly, and then use del statement or list Remove () or list Pop() to delete
Most lists change the list itself.
del.li [index], if there is no index, the list will be deleted
li.remove('element '), change the list itself, no return value, print and view
li. Pop (index). If there is no index, it will be deleted from the last one by default and printed for viewing
li = list('abcde') del li[1] # -->Delete by index, ['a ',' C ','d', 'e'] del li # -->Delete the entire list. NameError: name 'li' is not defined print(li) # Remove is deleted with a value. The change is the list itself, and there is no return value li.remove('c') # -->Print (Li. Remove ('c '), no return value print(li) # -->Delete by element, ['a ',' B ','d', 'e'] print(li.pop(3)) # -->d. Delete by index print(li.pop()) # -->e. Delete from last by default print(li) # -->After deleting the last element, the returned list ['a ',' B ',' C ','d']
Special operation of list (familiar)
List addition: Note: it is not the addition of corresponding positions, but splicing.
Multiply with integers, expand the list, and repeat the contents of the list. Note: the list cannot be multiplied by the list.
The list can only be spliced and expanded by multiple, and cannot be added, subtracted, divided, etc.
Member judgment
Whether the element is in the list, in, not in
Iteration, for traversing each element in the list,
for i in li
print i, quickly take out each element.
Common built-in functions (familiar)
len(), return length
max() returns the maximum value
min(), return the minimum value
python Built in methods or functions: print(type(len)) #--> builtin_function_or_method print(type(max)) #--> builtin_function_or_method print(type(min)) #--> builtin_function_or_method li = list("abcde") print(len(li)) #-->5. Return length, which can also be understood as the number of elements # String and string comparison ascii, compare one by one print(max(li)) # e print(min(li)) # a li_2 = ['a','c', 2, 1] print(max(li_2)) # Error reporting: int and str cannot be compared using > or < for comparison
Tips:
- The comparison between strings and characters is converted to ascii
- String and integer comparison error
- The above methods are all python built-in methods
Sorting and inversion of lists (familiar)
list.reverse(); list.[::-1], invert the list
list.sort(reverse=Fasle), sort, ascending by default
list.sort(reverse=True), sort, descending
Reverse order and sorting li_3 = [1, 2, 34, 4, 5, 6, 4, 7, 10] # Take out the whole list in reverse order print(li_3[::-1]) # --> [10, 7, 4, 6, 5, 4, 34, 2, 1] # 50. Reverse() -- > fetch in reverse order, no return value li_3.reverse() # -->No return value print(li_3) # --> [10, 7, 4, 6, 5, 4, 34, 2, 1] # Demand: li_3 sort # 50. Sort () defaults to ascending li_3.sort() # --> [1, 2, 4, 4, 5, 6, 7, 10, 34] li_3.reverse() # -->Result inversion after ascending # print(li_3[::-1]) # Reverse the ascending results with slices to get the descending results print(li_3) # -->Get the results in descending order [34, 10, 7, 6, 5, 4, 4, 2, 1] # 50. Sort (reverse = true) reverses the results sorted in ascending order -- > descending order li_3.sort(reverse=True) print(li_3) # -->Get the results in descending order [34, 10, 7, 6, 5, 4, 4, 2, 1]
Slice of list (key points)
slice(start, stop[, step]), slice, close left and open right, step size cannot be bit floating point number or bit 0.
reflection:
li = [1,2,3,4,5,6,7] take [2,3,4] and [2,4,6]
li = list("1234567") # [2,3,4] # Slices are separated by colons in English, L[start:stop:step] # The start position is 0, and the end position is the last one by default. The value is left closed and right open. The default step size is 1. It cannot be a floating-point number and cannot be 0 print(li[1:3]) # --> ['2', '3'] print(li[1:4:1]) # -->[2,3,4], or print(li[1:4]) # [2,4,6] print(li[1:6:2]) # --> [2,4,6] print(li[1::2]) # --> [2,4,6] Multiple list values li_2 = [1, 2, 3, ["amy", 1]] # From li_2 take out "amy" print(li_5[3][0]) # --> amy
List common operations (familiar)
Add:
50. Append (object) -- > add a new object at the end of the list, change the list itself, and print the list
50. Insert (index, object) -- > inserts an object into the list at a specified location
50. Extend (Iterable) -- > expand the original list with the new list. Only iteratable objects (list and string) can be passed, and a single value cannot be passed in
50. Copy() -- > copy list
Modification:
L [index] = data -- > modify the data of the specified index
delete
50. Pop ([index]) -- > removes an element in the list (the last element by default) and returns the value of the element
50. Remove (value) -- > removes the first match of a value in the list
50. Clear() -- > clear list
del L [index] -- > deletes the data of the specified index. After deletion, the data does not exist; If there is no index, delete the entire list
Find:
50. Index (value) -- > find the index position of the first matching item of a value from the list
Statistics:
50. Count (object) -- > count the number of times an element appears in the list. If a list is nested in the list, the nested list is taken as a whole, and the elements in it are not counted
Len (L) -- > list length
Sort:
50. Reverse() -- > reverses the order of the elements in the list
50. Sort (reverse = false) - > sort the original list in descending order
50. Sort() -- > sorts the original list in ascending order
li = list('12345') li.append(4) # ['1', '2', '3', '4', '5', 4] li.append([5, 5, 6]) # ['1', '2', '3', '4', '5', [5, 5, 6]], additional elements li.extend([5, 5]) # ['1', '2', '3', '4', '5', 5, 5], expand the list and pass in the iteratable object print(li) # Insert element in list li3 = ["happy","year"] li3.insert(1, "new") # ['happy', 'new', 'year', put the position first, and then the inserted content print(li3) # Count the number of occurrences of 3 li1 = [1, 2, 3, [3, 3]] print(li1.count(3)) # 1. The list is a whole. Element 3 appears only once and returns an integer # Index position of element li2 = [1, 2, 3, 2, 3, 2] # 2. Return the smallest index position of 3 in the list print(li2.index(3)) li4 = [1, 2, 3] del li4 # name 'li4' is not defined, delete the list, the whole list does not exist del li4[1] # [1, 3], delete element li4.clear() # [], clear the list and return an empty list print(li4)
Tuple
Tuple Introduction (Master)
Tuple is also a sequence structure, but it is an immutable sequence. You can simply understand it as a list with immutable content. Tuples are used in much the same way as lists, except that the internal elements cannot be modified.
Tuple creation (Master)
To create a tuple, just enclose the different data elements separated by commas in parentheses. We can also create tuples directly through tuple().
tu = () print(type(tu)) # < class' tuple '> empty tuple tu1 = (123) print(type(tu1), tu1) # < class' Int '> 123, the passed in object is an iteratable object, not an integer tu2 = (223,) print(type(tu2), tu2) # < class' tuple '> (223), when there is only one element, a comma must be added, tu3 = tuple("1234") print(type(tu3), tu3) # < class' tuple '> ('1', '2', '3', '4'), pass in an iteratable object
Tuple and list the same operation (familiar)
- Use square brackets and subscripts to access elements
- Slice (form new metagroup object)
- There are only two ways: tuple count() / tuple. index()
- Use python's built-in function: reversed(), sorted() to sort and reverse
- Addition and multiplication, like lists, realize splicing and expansion, and tuples cannot be added, subtracted, multiplied and divided
tu = tuple("123454545") print(tu[1]) # 2 subscript index value print(tu[2:4]) # ('3 ',' 4 ') slice value print(tu.count('5')) # 3 number of occurrences of digit 5 print(tu.index('5')) # 4 index of the first digit 5 # Tuples only have count and index methods. How to reverse the order? tu1 = (4, 3, 2, 5) print(tu1[::-1]) # Reverse (5, 2, 3, 4) print(tuple(reversed(tu1))) # Reverse (5, 2, 3, 4) print(list(reversed(tu1))) # Reverse [5, 2, 3, 4] to return to the list print(sorted(tu1)) # Sorting returns the list [2, 3, 4, 5]. The default is False, from small to large print(sorted(tu1, reverse=True)) # Sorting returns the list [5, 4, 3, 2], from large to small tu2 = (1, 2, 3) tu3 = (3, 4, 5) print(tu2 + tu3) # (1, 2, 3, 3, 4, 5) splicing print(tu2 * 3) # (1, 2, 3, 1, 2, 3, 1, 2, 3) extension
Operation not allowed in tuple (familiar)
Tuples are immutable types and can only be accessed and searched. Immutable parameters need to be passed in during data analysis. Tuples consume less memory than lists. It is recommended to use tuples when the incoming elements do not need to be changed; Use the list when the incoming element needs to be changed.
- It is not allowed to modify or add elements. (primary elements cannot be modified when they are tuples) can be spliced into new element groups
- Deleting an element is not allowed (but the whole tuple can be deleted)
tu = (1, 2, 3, 4) tu[1] = 2 # Non modifiable element print(tu) tu1 = tu + (5,) print(tu1) # (1, 2, 3, 4, 5) can be spliced to form a new tuple without modifying the elements in the tuple print(id(tu)) # 1815815693560 print(id(tu1)) # The memory address of 1815813796440 is different, which is equivalent to creating a new tuple tu1 = (1, 2, 3, ["name", 6]) # It can be modified. It is not allowed to modify only when the primary element is a tuple. tu1[3][0] = 5 print(tu1) # (1, 2, 3, [5, 6]) tu1 = (1, 2, 3, ("name", 6)) # Cannot be modified tu1[3][0] = 5 print(tu1) # TypeError: 'tuple' object does not support item assignment del tu1[1] # Deleting elements is not supported. TypeError: 'tuple' object doesn't support item deletion del tu1 # If the entire tuple is deleted, the tuple does not exist. NameError: name 'tu1' is not defined print(tu1)
In fact, tuples don't have any method to modify internal elements. For example, tuples do not have methods such as remove, append, pop, etc
Conversion between tuple and list (Master)
#Tuple to list tu = (1, 2, 3) print(list(tu)) # [1, 2, 3] # List tuple li = [0, 1, 2, 3] print(tuple(li)) #(0, 1, 2, 3)
Dictionary (dict)
Dictionary Introduction (mastery)
Python's dictionary data type is implemented based on hash algorithm. It adopts the form of key value pair (key:value), and calculates the address of value according to the value of key. It has very fast retrieval and insertion speed. It is a variable object, so it supports modification, insertion, deletion and other operations.
Dictionary creation (Master)
The first method:
test = {}
test = { key1 : value1, key2 : value2}
cpt = {"name": "Xiao Ming", ('hight'): 180, "hobbit": ["xuexi", "game"]} print(type(cpt), cpt) # < class' dict '{' name ':' Xiao Ming ',' high ': 180,' hobby ': [' Xuexi ',' game ']} cpt1 = {"addr": "henan", "addr": "hebei", "addr": "Beijing"} print(cpt1) # {'addr': 'Beijing'}
be careful:
- In Python 3 Starting from 6, the dictionary object will maintain the order of key value insertion, and it contains an unlimited number of elements. The type of value value can also be any other data type, list, integer, tuple, etc.
- The key of the dictionary must be immutable objects, such as integers, strings, bytes and tuples, but the most used is strings. Lists, dictionaries, collections, etc. cannot be used as keys. At the same time, the key in the same dictionary must be unique, but the value does not have to be. If there are duplicate values, they are overwritten.
The second method:
dict()
Method of dict(**kwargs) key value pair
Relation of dict(mapping) mapping
dic1 = dict(name="xiaoming", age=18) dic2 = dict([("name", "xiaoming"), ("age", 18)]) dic3 = {"name": "xiaoming", "age":18} print(dic1, dic2, dic3, sep="\n") # {'name': 'xiaoming', 'age': 18} print(dic1 == dic2 == dic3) # True
expand:
map(func,*iterables):
Transfer the elements in iterables to func one by one for processing
zip(iter1 [,iter2 [...]]):
zip object, package, package the one-to-one corresponding elements in the iteratable object into meta groups and return, package the corresponding elements in iter1 and iter2 into tuples, and then return the list composed of these tuples.
Exercise:
- 1.list('1234 ') -- > [1,2,3,4] -- > converts each element in li to int
# Requirement: list ('1234 ') -- > [1,2,3,4] -- > converts each element in li to int li = list('1234') print(type(li[0]), li) # < class' STR ', [' 1 ',' 2 ',' 3 ',' 4 '], elements are in the form of strings print(type(list(map(int, li))[0]),list(map(int, li))) #< class' Int '> [1, 2, 3, 4], the element is an integer # map(func,*iterables), which transfers every iteratable element in li to int
- 2. Convert the input 1 3 5 9 into an integer and present it in the form of a list
ipt = input("Please enter:") # 1 3 5 7 print(ipt.split(" ")) # ['1', '3', '5', '7'], string segmentation print(list(map(int, ipt.split(" ")))) # [1, 3, 5, 7], after conversion, it is stored in the list
- 3.li_k = ['name', 'age'] and li_v = ['xiaoming', 18] how to combine into a dictionary of key value pairs
li_k = ['name','age'] li_v = ['xiaoming', 18] print(zip(li_k, li_v)) # < zip object at 0x0000019e3b8e0348 >, zip object print(list(zip(li_k, li_v))) # [('name ',' Xiaoming '), ('age', 18)], list form print(dict(list(zip(li_k, li_v)))) # {'name':'xiaoming ','age': 18}, dictionary form print(dict(zip(li_k, li_v))) # {'name':'xiaoming ','age': 18} can also be presented directly in the form of a dictionary
ACCESS Dictionary (Master)
Dictionary is a collection type, not a sequence type, so there is no concept of index subscript, let alone slicing. However, similar to list, the dictionary takes the value by putting the corresponding key in square brackets to obtain the corresponding value.
For example: dic[exit_key], when the key value does not exist, the access will report an error
dic = {'name': 'xiaoming', 'age': 18} # print(dic[0]) # Error report, KeyError print(dic['name']) # xiaoming print(dic['sex']) # When accessing a nonexistent key value, an error KeyError will be reported
Addition and modification of Dictionary (mastery)
- Adding is to insert new key value pairs into the dictionary
- Modification is to give a new value to the original key. Since a key can only correspond to one value, if a key is assigned multiple times, the following value will overwrite the previous value
dic = {'name': 'xiaoming', 'age': 18} # Add value, take out assignment dic["sex"] = "famal" # {'name': 'xiaoming', 'age': 18, 'sex': 'famal'} # Modify the value, take it out and re assign it dic["age"] = 22 # {'name': 'xiaoming', 'age': 22, 'sex': 'famal'} print(dic)
A series of deletions (Master)
- Delete dictionary element: del dic[exit_key] or DIC pop(exit_key)
- Delete entire dictionary: del dic
- Empty the entire dictionary: DIC clear()
# Deletes the specified value dic = {'name': 'xiaoming', 'age': 18, 'sex': 'famal'} del dic['name'] # {'age': 18, 'sex': famal '}, delete value with key value print(dic) # To delete with pop, you must pass in parameters. The value deleted by pop can be printed print(dic.pop('age'),dic) # 18 {'name': 'xiaoming', 'sex': 'famal'} del dic # Delete entire dictionary print(dic) print(dic.clear(),dic) # None {}, clear the dictionary
Dictionary common operations (familiar)
D. Get (k [, D]) -- > returns the value of the specified key. If the value is not in the dictionary, it returns none
D. Items() -- > returns a list of traversable (key, value) tuple pairs, a mapping relationship, and a for loop
D. Keys() -- > returns all keys of the dictionary in a list
D. Values() -- > returns all values of the dictionary in a list
dic = {'name': 'xiaoming', 'age': 18, 'sex': 'famal'} print(dic.get('age')) # 18 print(dic.get('gender')) # None # Getting the value of a nonexistent key through [] will report an error, and the get method will return None print(dic.items()) # Mapping relationship, dict_items([('name', 'xiaoming'), ('age', 18), ('sex', 'famal')]) for key, value in dic.items(): print(key, value) # name xiaoming ; age 18 ; sex famal # Get all key s print(dic.keys()) # dict_keys(['name', 'age', 'sex']) # Get all value s print(dic.values()) # dict_values(['xiaoming', 18, 'famal'])
Homework exercise:
- Render lis1 and lis2 as key value pairs
# The first method is1 = ['name', 'author', 'introduce'] lis2 = ['NORWEGIAN WOOD', 'Harry Murakami', ' It"s a secret'] print(dict(zip(lis1, lis2))) # The second method: def f_map(a, b): return (a, b) print(dict(map(f_map, lis1, lis2)))
- Get xiaom_ key and value of info
xiaom_info = {'name': 'xiaoming', 'addr': 'henan', 'weight': 110} print(xiaom_info.keys()) # ['name', 'addr', 'weight'] print(xiaom_info.values()) # ['xiaoming', 'henan', 110]
Set
Collection Introduction (Master)
A set is a set of unordered and non repeating elements. Its basic functions include relationship testing and eliminating duplicate elements. It is a variable data type (addition, deletion, modification and query).
The core of collection data type is automatic de duplication.
Set creation (Master)
The collection uses braces {} to frame elements, separated by commas.
s = {ele1,ele2,ele3...}
s = set()
s = set(iterable), iterable (list, string)
{} does not create an empty collection, but an empty dictionary. set() is required to create an empty set
s = {} print(type(s), s) # Empty dictionary class' dict '{} s = set() print(type(s), s) # Empty set class' set '> set () s1 = set([1, 2, 3, 1, 2, 12, 13]) print(s1) # Automatic weight removal, {1, 2, 3, 12, 13} s2 = set('hello world') print(s2) # {'e', 'h', ' ', 'r', 'l', 'o', 'd', 'w'} # Take all strings apart, remove duplication and disorder
Add element (familiar)
Through set The add (key) method can add elements to the set
be careful:
- It can be added repeatedly, but the weight will be removed automatically, so it has no effect
- Mutable objects cannot be added
s1 = set([1, 2, 3, 4, 5, 12, 13]) s1.add(3) # Automatic weight removal {1, 2, 3, 4, 5, 12, 13} s1.add(8) # Successfully added {1, 2, 3, 4, 5, 8, 12, 13} s1.add('xiaoming') # The added element is of immutable data type {1, 2, 3, 4, 5, 8, 12, 13, 'xiaoming'} s1.add([1, 2, 3]) # Only immutable objects can be added, which is the same as the key of the dictionary. TypeError: unhashable type: 'list' print(s1) # Automatic weight removal, {1, 2, 3, 4, 5, 12, 13}
Collection Update (familiar)
You can use set Update () method to update another object to the existing collection. This process will also be de duplicated
s1 = set([1, 2, 3, 4, 5, 12, 13]) s1.update('hello') # {'h', 1, 2, 3, 4, 5, 12, 13, 'l', 'o', 'e'} # Update, such as the extension of the list and the extension of the collection, still de duplication, and disassemble each hello and add it to s1 print(s1)
Delete element (familiar)
- set.remove(key): deletes the specified element. An error is reported when the element does not exist
- set.pop(): randomly delete elements (Note: no parameters)
s1 = set([1, 2, 3, 4, 5]) s1.remove(3) # {1, 2, 4, 5} delete the specified element s1.remove('xiaoming') # Error when element does not exist s1.pop() # Randomly delete elements, demonstrated in ipython print(s1)
be careful:
The collection cannot take out an element (unordered and without the concept of subscript), because the collection does not support subscript index or dictionary retrieval through key value pairs.
Variable type and immutable type
View with id()
Variable type: change the data itself and the memory address remains unchanged. Add, delete, modify and query
list(), dict(), set() (store string, tuple, numeric value)
Immutable type: change data and memory address
Numeric value, string, byte, tuple (only available)