python - 计算列表python中的元素(字符串)
问题描述
genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']
# write function to count the number of specific genre in genres_list
def find_genre(genre):
count=0
for count in genres_list:
if count == genre:
count=count+1
return count
number=find_genre(pop)
print(number)
输出:
TypeError:只能将str(不是“int”)连接到str
解决方案
尝试这个。list
有一种计算元素出现次数的方法。
genres_list = ['rock', 'pop', 'folk', 'dance', 'rusrap', 'ruspop', 'world', 'electronic', 'alternative', 'children', 'rnb', 'hip', 'jazz','postrock', 'latin', 'classical', 'metal', 'reggae', 'tatar','blues','pop', 'jazz']
print(genres_list.count('pop'))
输出
2
list.count()
复杂度是O(n)
.
您可以编写自己的计数函数。
def find_genre(genre):
count=0
for _genre in genres_list:
if _genre==genre:
count+=1
return count
print(find_genre('pop'))
#2
timeit
分析一个大小为 200 万的列表。撰写本文时的结果(python 3.7,windows 10)
In [38]: timeit genres_list.count('pop') #My answer
26.6 ms ± 939 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [40]: timeit Counter(genres_list)['pop'] #Pitto's answer using collections.Counter
92.5 ms ± 751 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
现在,包括我在内的每个人都建议使用自定义计数功能。
def find_genre(genre):
count=0
for _genre in genres_list:
if _genre==genre:
count+=1
return count
In [42]: timeit find_genre('pop')
63.9 ms ± 803 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
只是为了比较(我不推荐使用)我写了一些其他的函数来计算计数。
In [36]: timeit sum(list(map(lambda x:x=='pop',genres_list)))
334 ms ± 13.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [37]: timeit len(list(filter(lambda x:x=='pop',genres_list)))
188 ms ± 18.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [44]: timeit ' '.join(genres_list).count('pop')
41.5 ms ± 2.6 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
您的代码中发生错误,因为您count
用于计算流派的计数并再次用作count
循环变量。在每次迭代中count
都变成 astr
并且我们不能添加str
到int
类型中。
推荐阅读
- c# - ASP.NET Core 相关字段为必填错误
- python - 需要帮助使用 python 创建圣诞树
- android - 为什么我的应用程序可以在模拟器上运行,但不能在发布模式下运行?
- c++ - 需要帮助来更正我的单向选择代码
- java - 无法让我的 API 数据显示在其他页面上
- python - 如何计算实例的索引?
- oauth-2.0 - 撤销 id 令牌 Google oauth2 java
- objective-c - 在命令行中打开的 MacCatalyst 应用程序中发送 HTTP 请求
- xml - XSLT - 仅首字母大写,但如何处理像 McDermott 这样的名字
- python - scipy 不使用 anaconda 的本地库作为 libgcc