我是python中的新手,现在我还在学习,我对字典有疑问。 我想创建用户将输入字符串的程序,然后它将计算该字符串中的字符。嗯也许我会用图片来解释 this is the preview about program that i want。我真的需要帮助,谢谢你们。顺便说一句,我使用python 3.6
答案 0 :(得分:0)
==> "china chinese"
(1) char-frequency dict:
{'n': 2, 'e': 2, 'a': 1, 's': 1, 'h': 2, 'c': 2, 'i': 2}
(2) frequency-char dict:
{1: ['a', 's'], 2: ['n', 'e', 'h', 'c', 'i']}
(3) result:
OrderedDict([(1, ['a', 's']), (2, ['c', 'e', 'h', 'i', 'n'])])
==> "united states"
(1) char-frequency dict:
{'n': 1, 'e': 2, 'a': 1, 's': 2, 'u': 1, 'd': 1, 'i': 1, 't': 3}
(2) frequency-char dict:
{1: ['n', 'a', 'u', 'd', 'i'], 2: ['e', 's'], 3: ['t']}
(3) result:
OrderedDict([(1, ['a', 'd', 'i', 'n', 'u']), (2, ['e', 's']), (3, ['t'])])
#!/usr/bin/python3
# 2017.10.30 19:10:16 CST
from collections import OrderedDict
def inverseCharFrequency(s):
print("\n\n==> \"{}\"".format(s))
## assert you are counting the lower letters
## get the char-frequency dict
char_freq = {}
for c in s:
if c >='a' and c <='z':
char_freq[c] = char_freq.get(c,0) + 1
## let's print
print("(1) char-frequency dict:\n{}".format(char_freq))
## get the frequency-char dict
char_freq2 = {}
for c, freq in char_freq.items():
if char_freq2.get(freq, None):
char_freq2[freq].append(c)
else:
char_freq2[freq] = [c]
## let's print
print("(2) frequency-char dict:\n{}".format(char_freq2))
## why do you want to sort? Ok, just sort!
res = OrderedDict()
for k in sorted(char_freq2):
res[k] = sorted(char_freq2[k])
## let's print
print("(3) result:\n{}".format(res))
return res
if __name__ == "__main__":
s = "china chinese"
res = inverseCharFrequency(s)
s = "united states"
res = inverseCharFrequency(s)