简体   繁体   English

使用 Python 计算单词中的字母

[英]count letter in words using Python

I am working with Python to write a function Here is an example: lettercount(['hello','it','is','me'],'i') should return ['it-1','is-1'] .我正在与 Python 一起写一个 function 这是一个例子: lettercount(['hello','it','is','me'],'i')应该返回['it-1','is-1']

Here is my code:这是我的代码:

def lettercount(list, letter):
    result = []           #create an empty list
    for word in list:            #traverse through all the words in the provided list
        if word not in result:        #from this line I don't know what I'm really doing though
            if letter in word:                
                wrd = "{}-".format(word).append(word.count(letter))     
 #tried to achieve the same format as provided but failed
                result.append(wrd)               #this is wrong because str doesn't have the attribute "append"
    return result        

Can someone give me a hint on this problem?有人可以给我提示这个问题吗? Thanks so much!非常感谢!

The problem is the way you construct wrd .问题是你构造wrd的方式。 Change this line -更改此行 -

wrd = "{}-".format(word).append(word.count(letter))     

To -到 -

wrd = f"{word}-{word.count(letter)}"

Ps please.请附言。 avoid using list as a name of a variable and use, for example, lst instead since list is a protected word in Python.避免使用list作为变量名,而是使用lst等,因为list在 Python 中是受保护的字。

def lettercount(lst, letter): out = [] for word in lst: cnt = sum(1 for l in word if l == letter) if cnt: out.append(f'{word}-{cnt}') return out

Try:尝试:

def lettercount(lst, letter):
    result = []
    for word in lst:
        if letter in word:
            result.append(word + '-' + str(word.count(letter)))

And I don't recommend naming variables "list" because it's an existing keyword in Python.而且我不建议将变量命名为“list”,因为它是 Python 中的现有关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM