正确使用min和list

2024-10-03 21:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

text = input("enter string:")
text.lower()
counta = text.count ("a")
counte = text.count ("e")
counti = text.count ("i")
counto = text.count ("o")
countu = text.count ("u")

if counta > 0:
print ("'a'",counta)

if counte > 0:
print ("'e'",counte)

if counti> 0:
print ("'i'",counti)

if counto > 0:
print ("'o'",counto)

if countu > 0:
print ("'u':",countu)


leastFreq = [counta,counte,counti,counto,countu]
leastFreq.sort()
while 0 in leastFreq: leastFreq.remove(0)
print (leastFreq)

任务=计算单词中的元音,打印出现频率最低的元音。在本例中,“potato”将打印:

'a' = 1
'0' = 2

我怎样才能让它只印“a”?我可以使用min(leastFreq),但它只返回值“1”。我怎么做,使它打印使用格式'a'=1或如果有一个以上的元音出现相同的数目。你知道吗


Tags: textinputstringifcountlowerprintenter
3条回答

要最小限度地更改代码:

leastFreq = [(counta, 'a'),(counte, 'e'),(counti, 'i'),(counto, 'o'),(countu, 'u')]
leastvowel = min(leastFreq)[1]

但是你应该改用collections.Counter

from collections import Counter
text = input("Enter text: ")
c = Counter(character for character in text if character in 'aeiou') #get counts of vowels
least_frequent = c.most_common()[-1]

least_frequent将是一个类似于('a', 1)的元组

编辑:如果您想要所有最常用的项目,可以使用itertools.groupby

lestfreq=list(next(itertools.groupby(c.most_common()[::-1], key=lambda x:x[1]))[1])

这看起来很复杂,但它所说的只是按排序顺序获取一个列表,并获取所有具有相同第二个值的元组,然后将它们放入一个列表中。你知道吗

计数器和运算符的组合可能会起到以下作用:

from collections import Counter
import operator
text = raw_input("enter string:")
freq = Counter(i for i in text if i in 'aeiou')
items = sorted(freq.items(),key=operator.itemgetter(1))
min = items[0][1]
for character,frequency in items:
    if frequency == min:
        print character,frequency

可以将^{}additional filter condition一起使用,测试元素是否为> 0

>>> leastFreq = [4, 2, 1, 0, 3, 0]
>>> min(x for x in leastFreq if x > 0)
1

但是这样,你就失去了这个计数属于哪个字符的信息。您可以创建一个dictionary,将元音映射到它们各自的计数,而不是五个不同的变量:

>>> text = "potato"
>>> counts = {c: text.count(c) for c in "aeiou"}
>>> counts
{'a': 1, 'i': 0, 'e': 0, 'u': 0, 'o': 2}
>>> counts["o"]
2

然后再次将min与生成器表达式和特定的key函数一起使用(按计数排序,而不是按元音本身排序)。你知道吗

>>> min((c for c in counts if counts[c] > 0), key=counts.get)
'a'

如果您对所有字母的计数感兴趣,也可以使用^{}。你知道吗

相关问题 更多 >