【发布时间】:2020-06-03 02:50:29
【问题描述】:
我的字符串为 Welcome to Datacurators.tech,我需要找出给定字符串中重复次数第二多的字符。我只需要使用基本的 python 代码(不要使用 import 或 def 函数)。我有下面的代码,但它给了我所有字符的计数。预期输出 (e,c,o,a) 输出可以是任何顺序。
stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
counts[i]=stri.count(i)
print (counts)
【问题讨论】:
-
如果你想计算频率然后,你可以制作直方图或使用
Counter(),我猜你不想要后者。 -
尝试检查
if i in counts:。如果是加一个;如果它没有设置为一个。 -
考虑通过 dict 将字符映射到出现计数,然后简单地使用 pythons sorted() 函数,它不需要任何包含。
-
接下来是排序并根据
asec\desc从排序列表\array中选择适当的1\-2索引。