Python basic exercises (2)

Python basic exercises (2)

Write a program to generate a list of 1000 random strings of length 2 consisting of "a-zA-Z0-9", count the number of occurrences of each string, and output the previous strings in descending order 10 strings and their number of occurrences.


import random
import string
def strge(n): #返回一个长度为n的,由“a-zA-Z0-9”组成的字符串
    str_list=[] #创建一个空列表
    for i in range(n): #列表的长度为n,里面接收“a-zA-Z0-9”中的任意两个
        str_list.append(random.choice(string.ascii_letters+string.digits))
    return ' '.join(str_list) #用join函数将列表中的元素转化为组合的字符串

def main():
    len=int(input('你需要字符串长度为:')) #从用户接收字符串长度
    ranstr_list=[] #创建一个空列表用来装字符串组合
    dict={
    
    } #创建一个空字典用来装随机生成的字符串和其出现次数
    for i in range(1000): #装入1000个字符串到列表里
        ranstr_list.append(strge(len))
    count=0 #定义count变量用来计数
    for j in set(ranstr_list): #将列表转化为集合,里边不存在重复元素,用j遍历
        for k in ranstr_list: #用k遍历列表
            if j==k:count+=1 #如果重复出现了,count自加1
        dict[j]=count #字符串是键,对应出现次数是值
        count=0 #避免重复计数,每个字符串找完后要清零
    order=sorted(dict.items(), key=lambda x: x[1], reverse=True)#比较字典中的值的大小,降序排列,返回一个元组列表
    for tuple in order[0:10]:#用切片输出前十个字符串及其出现的次数
        print(tuple[0],':',tuple[1])
if __name__=="__main__":
    main()

The results of the operation are as follows:
insert image description here
It took two and a half months to learn python, and corrections are welcome!

Guess you like

Origin blog.csdn.net/m0_65723013/article/details/127478888