我是python的新手,我试图获得这个名为fizz_count的函数,该函数将列表x作为输入,并返回该列表中字符串“fizz”的计数。但代码总是返回1.
到目前为止代码:
def fizz_count(x):
count = 0
for item in x:
if str(item).lower() == "fizz":
count += 1
return count
因此,当调用fizz_count(["fizz","buzz","fizz"])
时,代码应返回2.
答案 0 :(得分:4)
有一个漂亮的内置python函数叫count
,它实际上正是你正在寻找的东西:
def fizz_count(x):
return x.count('fizz')
每当对python有疑问时,请咨询the docs
JaredPar提出了一个有效的观点,如果你想让它与案例无关,那么你必须在这里使用列表理解。修改后的代码(添加了实用程序):
def fizz_count(x, search_string, case_insensitive=False):
if case_insensitive:
x = [item.lower() for item in x]
return x.count(search_string)
答案 1 :(得分:2)
它对我来说非常好。
正如@Slater Tyranus所写,使用当然list.count
- > fizzes.count('fizz')
。如果你想做一些更复杂的计数(如不区分大小写),列表推导可能对你有帮助。
>>> fizzes = ["fizz","buzz","fizz"]
>>> len([f for f in fizzes if lower(f) == 'fizz'])
2
或(感谢@iCodez):
>>> sum(1 for f in fizzes if lower(f) == 'fizz')
>>> from timeit import timeit
>>> fizzes = [u"fizz", u"buzz"] * 10000
>>> def fizz_for():
... count = 0
... for item in fizzes:
... if item == u"fizz":
... count += 1
... return count
...
>>> timeit('__main__.fizz_for()', setup='import __main__', number=1000)
1.393934965133667
>>> fizz_len = lambda: len([f for f in fizzes if f == u'fizz'])
>>> timeit('__main__.fizz_len()', setup='import __main__', number=1000)
1.3358290195465088
>>> fizz_sum = lambda: sum(1 for f in fizzes if f == u'fizz')
>>> timeit('__main__.fizz_sum()', setup='import __main__', number=1000)
1.7232561111450195
>>> fizz_count = lambda: fizzes.count(u'fizz')
>>> timeit('__main__.fizz_count()', setup='import __main__', number=1000)
0.44240689277648926
>>> timeit('__main__.fizz_for()', setup='import __main__', number=1000)
1.5867065230013395
>>> fizz_len = lambda: len([f for f in fizzes if f == 'fizz'])
>>> timeit('__main__.fizz_len()', setup='import __main__', number=1000)
1.2898265199983143
>>> fizz_sum = lambda: sum(1 for f in fizzes if f == 'fizz')
>>> timeit('__main__.fizz_sum()', setup='import __main__', number=1000)
1.5955777620001754
>>> fizz_count = lambda: fizzes.count('fizz')
>>> timeit('__main__.fizz_count()', setup='import __main__', number=1000)
0.3196232570007851
list.count
。sum
快。unicode
会使速度降低约30%(不在结果中,在本地检查)。