计算lis中某个项目的重复次数

2024-04-20 02:18:36 发布

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

l = "Hello world is me"
words_ = l.split()
print(l.split())

for item in words_ :
    if len(item) < 5 :
        print('Words with length less than 6:', item )
    elif len(item) == 5 :
        print('Words with length 5:', item )

这是我的代码,但是我希望它以指定的长度打印单词的数量,但是它会打印单词本身。有什么建议吗?你知道吗


Tags: inhelloforworldleniswithitem
3条回答

可以使用以下公式计算满足条件的元素数:

sum(condition for item in iterable)

请注意,这里的condition必须是布尔值(因为True1,而False0,所以它将True相加,从而计算满足条件的次数)。你知道吗

因此,如果要计算长度小于5的元素数,可以编写:

number_of_words = sum(len(word) < 5 for word in words_)

或长度为5的字数:

number_of_words = sum(len(word) == 5 for word in words_)

等等

您可以计算循环中的单词数,但使用根据单词大小过滤的生成器理解来输入sum更具python风格:

>>> l = "Hello world is me"
>>> sum(1 for w in l.split() if len(w)==5)
2

另一个变体是将测试结果转换为布尔值(这里测试的结果已经是布尔值,所以不需要bool()),然后求和:

sum(len(w)==5 for w in l.split())

它非常适合测试一个条件,但是如果您想一次性计算匹配多个条件(len < 5len == 5)的单词数,经典循环仍然是最佳选择,因为它只在列表上迭代一次,而且您自然会对if/elsif使用短路求值,这对listcomps来说太糟糕了,但这就是生命:

less_than_5=exactly_5=0
for item in l.split() :
    if len(item) < 5 :
        less_than_5 += 1
    elif len(item) == 5 :
        exactly_5 += 1

除了现有答案之外,还可以使用filterlambda函数来获取计数:

# Python 2.x
l = "Hello world is me"
words_ = l.split()
print "There are", len(filter(lambda x: len(x) < 5, words_)), "words less than 5 long"
print "There are", len(filter(lambda x: len(x) == 5, words_)), "words exactly 5 long"

# Python 3.x
l = "Hello world is me"
words_ = l.split()
print ("There are", len(list(filter(lambda x: len(x) < 5, words_))), "words less than 5 long")
print ("There are", len(list(filter(lambda x: len(x) == 5, words_))), "words exactly 5 long")

相关问题 更多 >