python3——字典(dict)小練習

題目要求1

數字重複統計:
(1).隨機生成1000個整數;
(2).數字的範圍[20,100];
(3).升序輸出所有不同的數字及其每個數字重複的次數;

代碼示例

import random
all_nums=[]
for item in range(1000):
    all_nums.append(random.randint(20,101))
sorted_nums=sorted(all_nums)
num_dict={}
for num in sorted_nums:
    if num in num_dict:
        num_dict[num]+=1
    else:
        num_dict[num]=1
print(num_dict)

運行結果

{20: 16, 21: 11, 22: 9, 23: 13, 24: 14, 25: 11, 26: 12, 27: 11, 28: 16, 29: 15, 30: 13, 31: 15, 32: 9,
 33: 9, 34: 10, 35: 13, 36: 11, 37: 15, 38: 14, 39: 12, 40: 13, 41: 14, 42: 12, 43: 6, 44: 12, 45: 14, 
 46: 11, 47: 11, 48: 9, 49: 11, 50: 7, 51: 11, 52: 15, 53: 12, 54: 12, 55: 16, 56: 8, 57: 10, 58: 16, 
 59: 14, 60: 8, 61: 12, 62: 13, 63: 13, 64: 12, 65: 12, 66: 13, 67: 14, 68: 5, 69: 13, 70: 7, 71: 11,
 72: 10, 73: 15, 74: 10, 75: 13, 76: 18, 77: 12, 78: 9, 79: 15, 80: 14, 81: 15, 82: 11, 83: 11, 84: 10, 
 85: 19, 86: 13, 87: 13, 88: 16, 89: 13, 90: 15, 91: 12, 92: 8, 93: 14, 94: 15, 95: 11, 96: 13, 97: 14, 
 98: 12, 99: 9, 100: 11, 101: 13}

Process finished with exit code 0

題目要求2

重複的單詞:此處認爲單詞之間以空格爲分隔符,並且不包括,和.#1.用戶輸入一句英文句子;
#2.打印出每個單詞及其重複的次數;

代碼示例

s=input('請輸入英文句子:')
s_li=s.split()
word_dict={}
for item in s_li:
    if item in word_dict:
        word_dict[item]+=1
    else:
        word_dict[item]=1
print(word_dict)

運行結果

在這裏插入圖片描述

題目要求3

1.生成100個銀行卡號:
 卡號以6102009開頭,後面3位依次是(001,002,003,......,1002.生成關於銀行卡號的字典,默認每個卡號的初始密碼爲‘Redhat’;
3.輸出卡號和密碼,格式如下:
卡號          密碼
6102009001   0000000

代碼示例

account_num=[]
for i in range(100):
    account_num.append('6102009%.3d'%(i+1))
account_info={}.fromkeys(account_num,'redhat')
print('卡號\t\t\t\t\t密碼')
for k,v in account_info.items():
    print(k,'\t\t\t',v)

運行結果

在這裏插入圖片描述
中間部分省略。。。。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章