Python字典的两道题目0330


第四题:


答案一:

dd = dict()
while True:
    key = input("存入的键:")
    value = input("存入的值:")
    dd[key] = value
    flag = input("是否继续存入[y/Y/N/n]:")
    if flag in ['n','N']:
        break
 
keys = list(dd.keys())
values = list(dd.values())
print(keys)
print(values)

答案二:

m = {}
while True:
    s = input("please input the key=value:")
    if '=' not in s:
        break
    k, v = s.split('=')
    m[k] = v
print(m)

第五题:


答案一:

letter = dict()
strs = input("输入一串字符串:")
 
for i in strs:
    letter.setdefault(i,0)
    letter[i] += 1
 
keys = list(letter.keys())
keys.sort()
for i in keys:    
    print(i,letter[i])


答案二:

from collections import Counter
s = 'asdfsdlkjlewjfklf'
print (dict(Counter(s)))

答案三:
>>> inStr = raw_input("Please INput")
Please INput123456abcabc
>>>counts = {}
>>>for i in inStr:
    counts[i] = counts.get(i, 0) + 1
>>>counts
{'a': 2, 'c': 2, 'b': 2, '1': 1, '3': 1, '2': 1, '5': 1, '4': 1, '6': 1}

阅读更多

没有更多推荐了,返回首页