开发者

Why do I get an AttributeError when using .count() in python

开发者 https://www.devze.com 2023-03-05 06:38 出处:网络
array1=[ 05666060680 19 247049 14 120 22 1710 19 6 17470 17 24069 22] i=0 while开发者_开发知识库 i<23

array1=[ 0 5 6 6 6 0 6 0 6 8 0 19 24 7 0 4 9 14 12 0 22 17 1 0 19 6 17 4 7 0 17 24 0 6 9 22]

i=0
while开发者_开发知识库 i<23
      m= array1.count(i)
      i=i+1

AttributeError: 'numpy.ndarray' object has no attribute 'count'

Why does attribute error appear when i use .count()? do I need to import something?


Well, according to the documentation, ndarray simply has no count method.

The code you have posted contradicts the error-message you give us. In your code you create a simple Python list, but your error message indicates that you are actually using a numpy ndarray.


First off all, your array is formatted weirdly, there should be commas between the numbers. Second, you are creating a numpy.ndarray from the numpy package, not a native python list. Use a python list, and it should work.


try to break line with "\"
and add "," between numbers.
How can I do a line break (line continuation) in Python?


What you try to do, can be done much more efficiently (Python 2.7 and above) by:

import numpy as np
from collections import Counter
array1= np.array([ 0,  5,  6,  6,  6,  0,  6,  0,  6,  8,  0, 19, 24,  7,  0,  4,  9, 14, 12,  0, 22, 17,  1,  0, 19, 6, 17,  4,  7,  0, 17, 24,  0,  6,  9, 22])
print Counter(array1.most_common(1))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号