List 2
One, additions, deletions and modifications
-
add - add element
1) List.append( element) - Add the specified element at the end of the specified list (does not generate a new list, but directly adds it to the original list)
heroes = ['ice shot', 'small cannon', 'Verus', 'Jinx', 'small method', 'card', 'Snake'] print(heroes) heroes.append('Juggernaut') print(heroes) heroes.append('piano girl') print(heroes)
Case: extract the failing scores in scores
scores = [89, 45, 99, 65, 93, 81, 29, 88, 76, 59, 66] new_scores = [] for s in scores: if s < 60: new_scores.append(s) print(new_scores)
Exercise 1: Use append to delete all odd numbers in the list
nums = [89, 45, 99, 65, 93, 81, 29, 88, 76, 59, 66] news_scores = [] for s in scores: if s % 2 != 0 new_scores.append(s) print(new_scores)
Exercise 2: Change all failing scores in scores to 'retest'
scores = [89, 45, 99, 65, 93, 81, 29, 88, 76, 59, 66] new_scores = [] for x in scores: if x < 60: new_scores.append('make-up exam') else: new_scores.append(x) print(new_scores)
2) List.insert( subscript, element) - Insert the specified element before the element corresponding to the specified subscript in the list
heroes = ['ice shot', 'small cannon', 'Verus', 'Jinx', 'small law', 'card', 'Snake'] print(heroes) heroes.insert(-1, 'Yasuo') print(heroes) heroes.insert(0, 'stone man') print(heroes)
2. delete - remove an element
1) del list [subscript] - delete the element corresponding to the specified subscript in the list
heroes = ['ice shot', 'small cannon', 'Verus', 'Jinx', 'small method', 'card', 'Snake'] print(heroes) del heroes[1] print(heroes) del heroes[1] print(heroes)
2) list.remove( element) - delete the specified element in the list (if the element does not exist, an error will be reported, if there are multiple elements, only the first one will be deleted)
heroes = ['ice shot', 'small cannon', 'Verus', 'Jinx', 'small method', 'Verus', 'card', 'Snake'] print(heroes) heroes.remove('small cannon') print(heroes) # heroes.remove('Tamm') # ValueError: list.remove(x): x not in list heroes.remove('Verus') print(heroes) # ['Ice Shot', 'Jinx', 'Little Fa', 'Verus', 'Card', 'Snake']
-
change - modify the value of an element
list[subscript] = new element - change the element corresponding to the specified subscript in the list to a new element
heroes = ['ice shot', 'small cannon', 'Verus', 'Jinx', 'small method', 'Verus', 'card', 'Snake'] print(heroes) heroes[1] = 'Sun Wukong' print(heroes)
Exercise: Modify all scores below 60 in scores to 0 (use change)
scores = [89, 45, 99, 65, 93, 81, 29, 88, 76, 59, 66] # method one for index in range(len(scores)): if scores[index] < 60: scores[index] = 0 print(scores) # Method Two for index, item in enumerate(scores): if item < 60: scores[index] = 0 print(scores)
Second, list related operations
-
list addition
list1 + list2 - combine two lists into a new list
A = [10, 20, 30] B = [100, 200] C = A + B # [10, 20, 30, 100, 200] print(C) print(A + A) # [10, 20, 30, 10, 20, 30]
-
list multiplication
list * N , N * list - repeats the elements of the list N times to produce a new element
C = A * 2 print(C) # [10, 20, 30, 10, 20, 30] print(B * 3) # [100, 200, 100, 200, 100, 200] print(['Xiao Ming', 'little flower'] * 3) # ['Xiaoming', 'Xiaohua', 'Xiaoming', 'Xiaohua', 'Xiaoming', 'Xiaohua']
-
list comparison operation
1) Compare equality: ==, ! =
print([10,20,30] == [10,20,30]) #True print([10,20,30] == [10,30,20]) #False
2) Compare size:>,<,>=,<=
List 1 > List 2
The size of the two lists is compared, and the size of the first pair of unequal elements is compared (elements at the same position are a pair)
print([10,20,30] > [1,100,200,300,400]) #True print([10,20,30] > [10,2,300,400,500]) #True
4.in and not in
element in list - checks whether the specified element exists in the list
element not in list - check if the specified element does not exist in the list
print(10 in [10,20,30]) print(10 in [10,20], 30) print([10,20] in [10,20,30])
Exercise: Already list A and B, print the common elements of A and B
A = ['Houyi', 'Zhen Ji', 'Luban No. 7', 'Zhao Yun'] B = ['little joe', 'Sun Wukong', 'Zhu Bajie', 'Houyi', 'shield mountain', 'Zhao Yun'] for x in A: if x in B: print(x)
Three, list related functions
1.sum (number sequence) - find the numerical sum of all elements of the number sequence
scores = [98, 23, 56, 88, 90, 70] result = sum(scores) print(result) result = sum(range(101)) print(result)
2.max,min
max( sequence) - find the largest element in the sequence
min( sequence) - Find the minimum element in the sequence
scores = [98, 23, 56, 88, 90, 70] result = max(scores) print(scores) result = min(scores) print(result)
Supplement: the logic of finding the maximum value
Assume that the first element is stored in the variable at its maximum, and then take out each subsequent element in turn and compare it with the stored maximum variable. If the value extracted later is greater than the maximum value, update the maximum value
scores = [98, 23, 56, 88, 90, 70] max1 = scores[0] for x in scores[1:]: if x > max1: max1 = x # update max print(max1)
3.sorted
1) sorted (sequence) - sort the elements in the sequence from small to large, and create a new list
scores = [98, 23, 56, 88, 90, 70] result = sorted(scores) print(scores) # [98, 23, 56, 88, 90, 70] # 2)sorted( sequence, reverse=True) scores = [98, 23, 56, 88, 90, 70] result = sorted(scores, reverse=True) print(scores)
4.len
len( sequence) - counts the number of elements in the sequence
print(len(scores)) print(len('abc123')) print(len(range(1, 100, 2)))
5.list
list( sequence) - Convert the specified sequence into a list (any sequence can be converted into a list, and the elements in the sequence are directly used as elements of the list when converting)
result = list('abc123') print(result) # ['a', 'b', 'c', '1', '2', '3'] result = list(range(5)) print(result) # [0, 1, 2, 3, 4]
Fourth, list related methods
list.xxx()
1. list.clear() - clears the list
nums = [10, 9, 89, 23] print(nums) nums.clear() print(nums)
2. List.count( element) - Count the number of specified elements in the list
nums = [10, 9, 89, 23] print(nums.count(100)) print(nums.count(9)) print(nums.count(10))
3. list.extend( sequence) - add all the elements in the sequence to the list
list1 = [10, 20] list1.extend([100, 200]) print(list1) # [10, 20, 100, 200] list1.extend('abc') print(list1) # [10, 20, 100, 200, 'a', 'b', 'c']
4. List.index( element) - Get the subscript corresponding to the specified element in the list (returns the subscript value starting from 0)
nums = [10, 9, 89, 23] # print(nums.index(100)) # ValueError: 100 is not in list print(nums.index(89)) # 2 print(nums.index(10)) # 0 print(nums.index(23)) # 3
5. List.reverse() - reverse the list
nums = [10, 9, 89, 23, 50] nums.reverse() print(nums)
List.sort() - Sort the elements in the list from small to large (directly modify the order of the original list elements)
list.sort(reverse=True) - sort the elements in the list from largest to smallest
nums = [10, 9, 89, 23, 50] result = nums.sort() print(nums) # [9, 10, 23, 50, 89] print(result) # None nums = [10, 9, 89, 23, 50] nums.sort(reverse=True) print(nums)
sorted( sequence) - Sort the elements in the list from small to large (do not modify the order of elements in the original sequence, but create a new list)
nums = [10, 9, 89, 23, 50] result = sorted(nums) print(nums) print(result)
Five, list assignment problem
Supplement: Variables in python save data, and the address of the saved data in memory (variables in python are all variables)
1. Copy and direct assignment
Requirement: A list is known, and now it is necessary to create a new list that is exactly the same as the original list
1) Direct assignment - one variable directly assigns a value to another variable, the address is assigned, and the two variables point to the same block of memory after assignment
nums2 = nums print('nums:', nums) print('nums2:', nums2)
2) copy
A variable assigns a value to another variable by copying. When assigning a value, it first copies the data in the original variable, creates a new data, and then assigns the memory address corresponding to the new data to the new variable.
nums3 = nums*1 print('nums3:', nums3) nums4 = nums + [] print('num4:', nums4) nums5 = nums[:] print('num5:', nums5) nums6 = nums.copy() print('num6:', nums6) print('----------------------------------------------------after modification-------------------------------------------------') nums.append(100) print('nums:', nums) print('nums2', nums2)
Six, list comprehension
The role of list comprehension: quickly create expressions for lists (succinct code)
1. List comprehension structure 1
1) Grammar:
[expression for variable in sequence]
2) Let the variables take values in the sequence, one by one, until the result is finished, calculate the result of the expression every time a value is taken, and use the calculation result as an element of the list
result = [10 for x in range(5)] print(result) # [10, 10, 10, 10, 10] result = [x*2 for x in range(5)] print(result) # [0, 2, 4, 6, 8]
Case 1: Multiply all elements in nums by 2
nums = [10, 23, 89, 67] result = [x**2 for x in nums] print(result)
Case 2: Get the single digits of all elements in nums
nums = [103, 230, 89, 67] result = [x % 10 for x in nums] print(result)
2. List comprehension
1) Grammar:
[expression for variable in sequence if conditional statement]
2) Let the variables take values in the sequence, take them one by one, until they are finished, each time a value is taken, it is judged whether the condition is true, and if it is true, the expression value is calculated as the element of the list
result = [x * 2 for x in range(5) if x % 2 == 0] print(result) # [0, 4, 8]
Case 1: Delete all failing scores in scores
scores = [80, 99, 23, 67, 56, 82, 76, 45] result = [x for x in scores if x >= 60] print(result)
Case 2: Extract the number of all odd numbers in nums
nums = [103, 230, 89, 67, 78] result = [x % 10 for x in nums if x % 2 != 0] print(result)