简体   繁体   中英

Using lambda function in generator expression

I am trying to count the total number of occurrences of a given val in the list using a lambda function:

def countOccurrence(givenList, val):
    result = sum(1 for i in range(len(givenList)) if lambda i: givenList(i) == val)
    return result

givenList = [3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]
print(countOccurrence(givenList, 5))

But the returned result is 16 , which is nothing but the length of the list.

如果您想计算列表中 5 的数量,您应该使用内置

 my_list.count(5)

Why use a lambda?

def countOccurrence(givenList, val):
    result = sum(1 for i in range(len(givenList)) if givenList[i] == val)
    return result

givenList = [3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]
print(countOccurrence(givenList, 5))

As is often the case in Python, the best way to do something its make use of its built-ins as much as possible because they've frequently been written in C. In this case that would be the count() method of sequence objects, my_list.count(5) as @Joran Beasley suggests in his answer .

Regardless, for future reference the code below shows how to use a lambda function in a generator expression like you where trying to do. Note that the lambda function needs to be defined outside of the expression itself and also what its definition needs to (because what you had wasn't quite correct).

def countOccurrence(givenList, val):
    check_list = lambda i: givenList[i] == val
    return sum(1 for i in range(len(givenList)) if check_list(i))

givenList = [3, 4, 5, 8, 0, 3, 8, 5, 0, 3, 1, 5, 2, 3, 4, 2]
print(countOccurrence(givenList, 5))  # -> 3


If you are trying to count the number of 5's in a list you should use the Counter. You get the numbers of all other elements as a bonus:

from collections import Counter
cntr = Counter(givenList)
#Counter({3: 4, 5: 3, 4: 2, 8: 2, 0: 2, 2: 2, 1: 1})
cntr[5]
# 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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