Day 11 of learning python
One week summary
This week we will mainly learn the content
-
list
-
tuple
-
character string
-
aggregate
-
Dictionaries
Mainly learn to master their operations and functions
The first is the list
list
The list supports functions such as adding, deleting, modifying and querying,
section
-
Syntax ------ > [start: end: step]
-
Slice category: local slice, all slice, step and no step, and reverse slice
operation
-
Repeat operation ----- -- > output list
-
Member operation ----- -- > output Boolean value
-
Merge operation -------- > output list
-
Compare --------- > output Boolean
function
-
There are two common methods for adding elements - > Instert and appdend
-
There are two common methods to delete elements - > pop and remove
-
Empty list ------------------------ > clear
-
Slicing is also a lookup element, as well as an index lookup
Use list
-
Reverse list
Use reverse slicing, or use functions directly
items = items[::-1] print(items) items.reverse() print(items)
-
Sort list
Note whether it is required to be in positive or reverse order
The default is positive order
items.sort(reverse=False) print(items) items.sort(reverse=True) print(items)
-
Format definition list
- Direct loop a number interval
- Conditionally select from a number range
- Random selection from a number range
nums = [i for i in range(1, 10)] nums = [i for i in range(1, 100) if i % 5 == 0 or i % 3 == 0] nums = [random.randrange(1, 100) for _ in range(10)]
practice
- Simple selection sort -------- -- > select the minimum value from the remaining elements each time
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73] for i in range(len(nums) - 1): # Suppose the first element is the minimum min_value, min_index = nums[i], i # Loop to find if there is a smaller value and note its position for j in range(i + 1, len(nums)): if nums[j] < min_value: min_value, min_index = nums[j], j # Change the minimum value to the previous position nums[i], nums[min_index] = nums[min_index], nums[i] print(nums)
-
Bubble sort -------- -- > compare elements in pairs. If the previous element is larger than the following element, exchange the positions of the two elements
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73]Add a condition to identify whether the list is sorted in advance
Num = [2, 3, 4, 5, 6, 7, 8, 9, 1] row once
By verifying whether there is element exchange position in the second cycle, it is speculated whether the list will be in good order
For example, special cases
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73] for i in range(1, len(nums)): swapped = False for j in range(0, len(nums) - i): if nums[j] > nums[j + i]: nums[j], nums[j + i] = nums[j + i], nums[j] swapped = True if not swapped: break print(nums)
Sampling and disorder
-
sample function no return sampling
-
The function can sample multiple elements of the list at the same time and put them back. (you can repeatedly draw) choices
-
The function can randomly extract an element choice from the list
-
Use the function to randomly disrupt the order of elements in the list, random shuffle()
tuple
Immutable container. Note that a tuple must have a comma, otherwise it will be regarded as a string. Tuples only support viewing,
operation
The operation of tuples will not change the original tuples, but only form new tuples, which has the same effect as list output
- Member operation
- Repeat operation
- Merge operation
other
-
Index and slice (same format as list)
-
Find the index where the element is located, fruits3 index()
-
Calculates the number of occurrences of an element in a tuple. Fruits 3 count()
character string
Note: the string is also an invariant data type, and can only be read, not rewritten
operation
String operation will not change the original tuple, but will form a new string, which has the same effect as list output
- Repeat operation
- Member operation
- Comparison operation
String operation
toggle case
-
Capitalize
print(a.upper()) -
Turn lowercase
print(a.lower()) -
title case
print(a.capitalize()) -
Capitalize each word
print(a.title())
Detection string
The operation of finding whether there is a substring in a string index / rindex find / rfindString placement
# Center print(a.center(80, '=')) # Right align print(a.rjust(80, '=')) # Align left print(a.ljust(80, '=')) b = '1234' # Zero fill (fill 0 on the left) print(b.zfill(6)) # Build left space print(email.strip()) # Right space of sleeve arrow print(email.rsplit()) # Use the specified content with... replace print(meat.lstrip('replace content').replace('replace content', '*'))
Explode and connect strings
content = 'You go your way, I will go mine.' content2 = content.replace(',', '').replace('.', '') # Remove the specified element from the string. Here are commas and periods print(content2) # Split string words = content2.strip() for word in words: print(word) # Split strings with commas words = content2.strip(',') for word in words: print(word) # Split the string with spaces up to three times items = content2.split(' ', maxsplit=3) print(items, len(items)) # Split the string with spaces from right to left, up to three times item = content2.rsplit(' ', maxsplit=3) print(item, len(items)) contents = [ 'Please don't believe my beauty', 'Don't believe my love', 'Because under the painted face', 'With a Playboy's heart' ] # Connects the elements in the list with the specified string print(','.join(contents))
Convert string encoding
Encoding: to convert a string set into another character set
Decoding: converting one character set into another string set
main points:
1. When selecting character set encoding, the best choice is utf-8 encoding by default
2. The character set of encoding and decoding shall be consistent, otherwise there will be garbled code
3. You cannot save Chinese with ISO-8859-1 code, otherwise there will be a coding black hole and Chinese will become a question mark
4. UTF-8 is not only an implementation scheme of Unicode, but also a variable length encoding. It has at least one byte and at most four bytes. It represents Chinese with three bytes
5. If the encoding and decoding methods are different, a Unicode decodeerror exception may be generated in python
6. There may also be garbled code
String encryption
For example, the Caesar code
Caesar password - a way to encrypt plaintext by replacing the corresponding characters
abcdefghijklmnopqrstuvwxyz
defghijklmnopqrstuvwxyzabc
Plaintext: attack at dawn
Ciphertext: dwwdfn dw gdzq
Symmetric encryption: secret and decryption use the same key
Asymmetric encryption: encryption and decryption use different keys (public key and private key) - -- > suitable for Internet applications
message = 'attack at dawn' # Generate a cross reference table for string conversion table = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'defghijklmnopqrstuvwxyzabc') # The translate method of string realizes string conversion print(message.translate(table))
aggregate
The definition of set is roughly the same as that of set learned in middle school
Set operation
-
Member operation ----- -- > output Boolean value
-
Intersection operation -------- > Set1 & set2, Set1 intersection(set2
-
Union operation -------- > Set1 | set2, Set1 union(set2)
-
Difference set operation -------- > Set1 - set2, Set1 difference(set2)
-
Symmetry difference -------- > Set1 ^ set2, (Set1 | set2) - (Set1 & set2),, Set1 symmetric_ difference(set2)
Operation of collection
set1 = {'apple', 'banana', 'strawberry'} print(set1) # Add element set1.add('blueberry') set1.add('waxberry') print(set1) # Delete element (random) print(set1.pop()) print(set1) # Delete element, specify delete set1.discard('apple') # Empty collection set1.clear()
Dictionaries
An element consists of a key and a value. The front of a colon is called a key and the back of a colon is called a value
Create dictionary syntax
-
literal syntax
-
Constructor syntax
-
Generative grammar
Traversal dictionary
- Traverse keys in the dictionary
- Traverse the values in the dictionary
- Traverse keys and values in the dictionary
Dictionary related operations
be careful:
1. The index operation of the dictionary is placed to the left of the assignment operation,
2. If the key corresponding to the index exists, its value is updated
3. If there is no corresponding index in the dictionary, a new set of key value pairs is added
4. Merge key value pairs, and the same key is updated
5. To delete an element, the key must exist, or an error will be reported
# The last item is deleted by default dict1.popitem() # Empty dictionary dict2.clear() print(dict1) dict1.setdefault('C', 800) # It's useless here print(dict1) dict1.setdefault('F', 1000) # Add a key value pair here print(dict1)
Summary of related topics
Select several typical explanations
Simple sort
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73] for i in range(len(nums) - 1): # Suppose the first element is the minimum min_value, min_index = nums[i], i # Loop to find if there is a smaller value and note its position for j in range(i + 1, len(nums)): if nums[j] < min_value: min_value, min_index = nums[j], j # Change the minimum value to the previous position nums[i], nums[min_index] = nums[min_index], nums[i] print(nums)
Bubble sorting
nums = [35, 12, 99, 58, 67, 42, 49, 31, 73] for i in range(1, len(nums)): for j in range(0, len(nums) - i):#Cyclic n-1ci if nums[j] > nums[j + i]:#Compare size nums[j], nums[j + i] = nums[j + i], nums[j]#Put the big one in the back print(nums) #exceptional case nums = [9, 2, 3, 4, 5, 6, 7, 8] for i in range(1, len(nums)): swapped = False for j in range(0, len(nums) - i): if nums[j] > nums[j + i]: nums[j], nums[j + i] = nums[j + i], nums[j] swapped = True if not swapped: break print(nums) nums = [2, 3, 4, 5, 6, 7, 8, 9, 1] for i in range(1, len(nums)): swapped = False for j in range(0, len(nums) - i): if nums[j] > nums[j - i]: nums[j], nums[j - i] = nums[j - i], nums[j] swapped = True if not swapped:#It ends when swaped no longer changes yes, that is, False break print(nums)
Lucky woman problem
15 men and 15 women were in the same boat at the same time. Now the ship is broken, 15 people need to be thrown down, and the other 15 people can be saved., So 15 men and 15 women were disorganized in order to form a circle.. Designate a person as the first. Count from one to nine. The man who counted ninth was thrown into the sea. What is the position of the requester to ensure that 15 women are on the ship. After counting the wine, count from the beginning
persons = [True] * 30 index, counter, number = 0, 0, 0 # Index, counter, count off while counter < 15:#Use the number of people thrown into the sea as the key to stop the cycle if persons[index]: number += 1 if number == 9: persons[index] = False#On the count of nine, he was thrown into the sea counter += 1#Add one to the number of people thrown into the sea number = 0 pass index += 1 if index == 30: index = 0#When the last person finished counting, the index started from scratch for person in persons: # if person: # print('female ', end =' ') # else: # print('male ', end =' ') # Ternary conditional operation ------ > the expression after if is True, take the value before if, otherwise take the value after else print('female' if person else 'male', end='')#Equivalent to the notes above #Simplified version person = [i for i in range(30)]#Put 30 people on the list in turn for _ in range(15): person = person[9:0] + person[:8]#Every 9 slices, add the list slices before and after 9, and put the front ones behind to form a new list. Slice again in the same way and cycle for 15 times for i in range(1, 31): print('female' if i in person else 'male', end='')
Licensing issues
import random porke_numbers = [i for i in range(2, 11)] flower_porkes = ['A', 'J', 'Q', 'K'] porke_numbers += flower_porkes #Determine the card type of the same suit, poker type, 2 ~ 10, AJKQ # print(porke_numbers) porke_nums = [] color_porkes = ['♥', '♣', '♦', '♠']#Designs and colors can be typed using the computer's own input method for color_porke in color_porkes:#Traversal Decor for porke_number in porke_numbers:#Traverse poker numbers porke_nums.append(color_porke + str(porke_number))#Combine decors and numbers # porke_nums.append(f'{color_porke}{porke_number}') # porke_nums = [f'{color_porke}{porke_number}' for color_porke in color_porkes for porke_number in porke_numbers ] porke_nums.append('king') porke_nums.append('Xiao Wang') # print(porke_nums) random.shuffle(porke_nums)#Use to disrupt the order of list elements # print(porke_nums) # print(len(porke_nums)) # player1.append(porke_nums[51:54]) # print(player1) player1 = [] player2 = [] player3 = [] for i in range(0, len(porke_nums) - 3, 3):#Subtract three and give the next three to the first player player1.append(porke_nums[i])# The cycle takes three poker at a time, so the cycle step is three player2.append(porke_nums[i + 1]) player3.append(porke_nums[i + 2]) player1 += porke_nums[52:54]#, give the last three to the first player # for _ in range(17): # player1.append(porke_nums.pop()) # player2.append(porke_nums.pop()) # player3.append(porke_nums.pop()) # player1 += porke_nums # player1.extend(porke_nums) player1.sort(key=lambda x: x[1:])#Here you can not know the principle, just know the function, and you will learn later. The function is to compare the size of the poker sent to your hand and sort it out player2.sort(key=lambda x: x[1:]) player3.sort(key=lambda x: x[1:]) for card in player1: print(card, end=' ') print() for card in player2:#Traverse the poker in the player's hand and output it print(card, end=' ') print() for card in player3: print(card, end=' ') print() #Simplified output format
De repeating element
nums = [2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 5, 3, 3, 8, 6, 9] counts = [] for num in nums: if num not in counts:# If there is no element in the empty list in the original list, add this element to the empty list, counts.append(num) print(counts)
Find the duplicate element with the most occurrences
Note: there may be more than one
nums = [2, 3, 4, 4, 4, 5, 6, 7, 8, 9, 4, 5, 5, 3, 3, 8, 6, 3, 3, 4] sum = []#Define the elements that appear most in an empty list max_apper = nums.count(nums[1])#First, assume that the first element appears the most for num in nums:#The loop list compares the number of occurrences of each element at a time if max_apper < nums.count(num):#Assign the number of occurrences to the initial value sum.clear()#If you find the new element that appears most, you need to clean up the previously saved elements max_apper = nums.count(num)#Load new elements into the list sum.append(num) elif max_apper == nums.count(num): if num not in sum:#If you find an element that is not the same as the current maximum number of occurrences, it will be placed in the list together, sum.append(num) print(f',The most common element is{sum}Output{max_apper}second')
Yang Hui triangle
nums = [1] for _ in range(0, 20): order = [] print(nums) for j in range(0, len(nums) + 1): if j == 0: order.append(nums[j]) elif j == len(nums): order.append(nums[len(nums) - 1]) else: order.append(nums[j] + nums[j - 1]) nums = order
Find problems
Enter a paragraph of English and use a dictionary to indicate the number of times each letter is selected. Put case in the same category
man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure. take as an example
import string sces = 'man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.' dict1 = {i: 0 for i in string.ascii_lowercase}# Format the output, import 26 letters into the dictionary to become the key of the dictionary, and the value of the dictionary is 0 for sce in sces: if sce in dict1: sces.count(sce)# Count the number of letters dict1[sce] = sces.count(sce) for key, value in dict1.items(): print(f'{key} {value}')
Stock analysis
stocks = { 'AAPL': 191.88, 'GOOG': 1186.96, 'IBM': 149.24, 'ORCL': 48.44, 'ACN': 166.89, 'FB': 208.09, 'SYMC': 21.29 } stocks1_new1 = {key: value for key, value in stocks.items() if value > 100} print(stocks1_new1) print(max(zip(stocks.values(), stocks.keys()))[1]) # The key and value exchange order of the dictionary is packaged to form a binary. The tuple can use the max and min functions # Moreover, when packaging, the exchange order is to directly compare their values, and then find the one with the largest value. One line of code directly handles the key value pair. At this time, the key value pair value is in the front, the key is in the back, and what we want is the key. Therefore, when we count to the second, the index is one print(min(zip(stocks.values(), stocks.keys()))[1]) print(max(stocks, key=stocks.get)) # Although Max and min cannot be directly used to compare key value pairs, they can selectively compare the max function, and then directly specify the value corresponding to the key for comparison print(min(stocks, key=stocks.get)) print(sorted(stocks, key=stocks.get, reverse=True)) # Sorting is similar to the second method of finding the largest, but note that here is sorted!!!! print(sorted(stocks, key=stocks.get, reverse=False))
summary
There are still a lot of contents this week, but if you study and practice carefully every day, the digestion of each day will be greatly reduced. You may not pay attention to how much you have got after a week's study, but the summary review at the weekend can summarize the knowledge you have learned, and realize how much you have mastered and how much you haven't mastered, just focus on review
I have carefully summarized it for a long time and left your valuable praise 👍 Let's go again