小白自学python
问题描述:
str = input("请输入一个字符串:")
print("不重复的字符是:")
count= {}
for word in str:
count[word] = count.get(word,0) + 1
items = list(count.items())
items.sort(key = lambda x:x[1],reverse = True)
for i in range(len(items)):
word ,count= items[i]
print(word,end='')
代码没问题,但是想让先出现的字母输出,比如输入字符串agh ggah h比a后出现所以想让h先输出,但是上面程序只能让h后输出,求大佬改改
答
string = input("请输入一个字符串:")
print("不重复的字符是:")
count = {}
# 累计循环写入dict()
for word in string:
count[word] = count.get(word, 0) + 1
print(count)
# 最终count的结果为: {'a': 2, 'g': 3, 'h': 3, ' ': 2}
items = list(count.items())
print('items: ', items) # 结果为: [('a', 2), ('g', 3), ('h', 3), (' ', 2)]
items.sort(key=lambda x: x[1], reverse=True) # 根据元组中下标为1的进行排序,也就是数字排序
print('sort: ', items) # 排序之后的结果为: [('g', 3), ('h', 3), ('a', 2), (' ', 2)]
for i in range(len(items)):
word, count = items[i]
print("--------------------------------------")
print()
print(word, end='') # 表示 a g h 空格(所以你最终的输出是根据排序后的内容输出的)
print()
print("--------------------------------------")
# 最终没太理解你的需求是什么?