正确使用min与列表

时间:2016-11-14 20:44:50

标签: python python-3.x

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)

task =计算单词中的元音,打印出现的最不常见的元音。在这种情况下,"马铃薯"会打印:

'a' = 1
'0' = 2

我如何制作它以便打印出来' a'?我可以使用min(leastFreq),但这只会返回值" 1"。我该怎么做才能使用格式' a' = 1或者是否存在多个具有相同出现次数的元音。

3 个答案:

答案 0 :(得分:0)

您可以将minadditional 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'

如果您对所有字母的数量感兴趣,您也可以使用collections.Counter

答案 1 :(得分:0)

Counter和operator的组合可能会起到作用:

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

答案 2 :(得分:0)

最低限度地更改您的代码:

arm64

但您应该使用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

这看起来很复杂,但它所说的是按排序顺序列出一个列表,并将所有具有相同第二个值的元组放在一个列表中。