简体   繁体   中英

Why count doesn't work for this list?(in python)

In the following code the result in "countOf1" is 0 instead of 12. What is the reason and how can i solve it?

import numpy as np
import pandas as pd
x = np.matrix(np.arange(12).reshape((1, 12)))
x[:,:]=1
countOf1=(x.tolist()).count(1)

It's because when you convert that into a list with tolist() you're getting a subset of a list. Meaning this is your x :

x.tolist()
Out[221]: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

To get your countOf1 to work you'll need to do it for x.tolist()[0] . This will give you:

x.tolist()[0].count(1)
Out[223]: 12

Remember that a numpy matrix is like a list of lists. Even though you only created one row vector, numpy writes it with 2 brackets ([[0,1,2,3,4...,11]]). So when you changed it to a list with tolist(), you created a list within a list. Since the list within the list != 1, the count is 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM