Use Python to generate a string of 1000 random characters, and then count the number of occurrences of each character. (using a dictionary)

#Import the random module and string module
 import random
 import string
 Wei string.ascii_ Letters stands for 26 upper and lower case letters
 Wei string.digits Represents 10 Arabic numerals
 Wei string.punctuation Represents punctuation characters
 x = string.ascii_letters + string.digits + string.punctuation
 #Use the list derivation to cycle 1000 times, and take a random number from X each time
 y = [random.choice(x) for i in range(1000)]
 #Use the join function to connect the extracted data into a string
 z = "".join(y)
 new_dict = dict()
 #Key points: loop traversal saves the extracted characters as key to the dictionary, and the number of times each character appears as value
 #Here we should understand what "dictionary. Get (parameter 1, parameter 2)" means
 #- > parameter 1 means: key value,
 #- > parameter 2: if the value of the specified key does not exist, the default value is returned (parameter 2)
 for a in z:
     new_dict[a] = new_dict.get(a, 0) + 1

This question is still difficult. The focus is on line 20. What does “dictionary. Get (key, default)” mean

Recommended Today

Simple use of gitbook

Basic use install Note that users need to install nodejs first, so that they can use NPM to install gitbook. npm install gitbook -g //View installed versions gitbook -V initialization //Create directory mkdir pfinal-club //Initialize books gitbook init structure Use the following command to generate a_bookDirectory, the content of which is the resource file of […]