[英]Counting element in python Deque
I've attempted to count 1 values within my deque
( ie deque.count(1)
) but get the following error: 我试图对我的
deque
1个值( 即 deque.count(1)
)进行计数,但出现以下错误:
'deque' object has no attribute 'count'
I assume that I am working with a Python version that's before 2.7 when the deque.count()
function was first introduced. 我假设我正在使用2.7之前的
deque.count()
函数首次引入时的Python版本。
Besides using a for
loop , what would be the most efficient/fastest way of counting how many 1's there are in my deque
? 除了使用
for
循环外 ,计算我的deque
有多少个1的最有效/最快的方法是什么?
“无循环”的要求很奇怪,但是如果您好奇的话...
len(filter(lambda x: x == 1, d))
I know you asked for no for
loops, but I don't think there's any other way: 我知道您不
for
循环,但我认为没有其他方法:
def count(dq, item):
return sum(elem == item for elem in dq)
For example: 例如:
>>> from collections import deque
>>> d = deque([1, 2, 3, 1])
>>> count(d, 1)
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.