首页 > 解决方案 > 计算列表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

标签: pythonpython-3.xstringlistcount

解决方案


尝试这个。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并且我们不能添加strint类型中。


推荐阅读