创建一个计算特定长度列表中的单词/字符串的函数-Python 3
尝试创建一个单词计数函数,该函数将计算给定长度的单词在列表中的数量创建一个计算特定长度列表中的单词/字符串的函数-Python 3,python,Python,尝试创建一个单词计数函数,该函数将计算给定长度的单词在列表中的数量 my_list =['full', 'hello', 'light', 'too', 'wise'] 如果我想在列表中搜索4个字母的单词……我在想: def word_count(list, length): count = 0 if len(list) == 3: #I know this is wrong #it's just an example of wh
my_list =['full', 'hello', 'light', 'too', 'wise']
如果我想在列表中搜索4个字母的单词……我在想:
def word_count(list, length):
count = 0
if len(list) == 3: #I know this is wrong
#it's just an example of what I was thinking
count += 1
return count
感谢您的帮助 试试看,它更像蟒蛇:
def word_count(word_list, word_length):
return len(filter(lambda x: len(x) == word_length, word_list))
这是你想要的吗
def countWordlen(lst):
count = 0
for i in lst: # loop over the items of the list
if len(i) == 3: # if the len the items (words) equals 3 increment count by 1
count = count + 1
return count
lst =['full', 'hello', 'light', 'too', 'wise']
countWordlen(lst)
OUT: 1
@Mbruh你就快到了,你只需要循环浏览整个列表,就像
my_list =['full', 'hello', 'light', 'too', 'wise']
def word_count(list, length):
count=0
for word in list:
if len(word)==length:
count=count+1
return count
word_count(my_list,4)
2
您好@matt-m,您在提交代码之前测试过代码吗?在请求帮助之前测试它总是很好的。是的,对不起,我以后会这么做。我尝试了很多不同的方法,但就是想不出来。谢谢!我对循环遍历列表一事一无所知。顺便说一句,不要这样做。这是非常低效的。@AndreyShipilov不要只说它低效……用例子支持你的想法……这样我们就可以从你的专业知识中学习……除此之外……遵循他试图做的事情首先,PEP8完全不用,使用保留字。其次,整个函数可以这样编写:def word\u countword\u list,word\u length:return lenfilterlambda x:lenx==word\u length,word\u list,它保存了不必要的变量定义和作用域。所以它的问题是不遵循PEP8?额外变量?计数,列表?您的答案具有相同的变量。。哪一个保留词?如果你在谈论保留词,请检查你答案中的论点…?旁边是他的例子…它遵循他希望实现的目标…尽管向他展示做事情的最佳方式是好的…但是再次…一个人不应该只说没有有效论点的话