为什么下面的 Python3 列表计数方法不起作用。?
why is the below list count method for Python3 not working.?
我正在尝试使用 list.count() 方法,但是我在输出中得到的计数为 0,这不应该发生。
basket=[1,8,4,3,6,4,5]
count=basket.count([4, 8])
print(f'The count of {basket[6]} & {basket[2]} is',count)
输出显示为 0,而应为 1 和 2
他们是我做错了什么吗?
list.count(x)
Return the number of times x
appears in the list.
因此 basket.count([4, 8])
将计算整个列表 [4, 8]
在 basket
中出现的次数。 basket
根本不包含 任何 列表,所以你得到零。
count([4, 8])
检查列表中是否存在 [4, 8]
,它为零。
求 4,8 的个数:
basket=[1,8,4,3,6,4,5]
print(f'The count of {basket[2]} & {basket[1]} is',','.join(str(basket.count(i)) for i in [4,8]))
或者简单地说:
from collections import Counter
count = Counter(basket)
print('The count of 4 & 8 is',count[4],',',count[8])
添加到@Joshua Varghese 的答案 - 使其完全按照您的预期方式工作:
from collections import Counter
from operator import itemgetter
basket=[1,8,4,3,6,4,5]
count=itemgetter(4,8)(Counter(basket))
print(f'The count of {basket[5]} & {basket[1]} is',count)
打印:
The count of 4 & 8 is (2, 1)
我正在尝试使用 list.count() 方法,但是我在输出中得到的计数为 0,这不应该发生。
basket=[1,8,4,3,6,4,5]
count=basket.count([4, 8])
print(f'The count of {basket[6]} & {basket[2]} is',count)
输出显示为 0,而应为 1 和 2
他们是我做错了什么吗?
list.count(x)
Return the number of times
x
appears in the list.
因此 basket.count([4, 8])
将计算整个列表 [4, 8]
在 basket
中出现的次数。 basket
根本不包含 任何 列表,所以你得到零。
count([4, 8])
检查列表中是否存在 [4, 8]
,它为零。
求 4,8 的个数:
basket=[1,8,4,3,6,4,5]
print(f'The count of {basket[2]} & {basket[1]} is',','.join(str(basket.count(i)) for i in [4,8]))
或者简单地说:
from collections import Counter
count = Counter(basket)
print('The count of 4 & 8 is',count[4],',',count[8])
添加到@Joshua Varghese 的答案 - 使其完全按照您的预期方式工作:
from collections import Counter
from operator import itemgetter
basket=[1,8,4,3,6,4,5]
count=itemgetter(4,8)(Counter(basket))
print(f'The count of {basket[5]} & {basket[1]} is',count)
打印:
The count of 4 & 8 is (2, 1)