简体   繁体   English

为什么计数不适合此列表?(在python中)

[英]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? 在以下代码中,“ countOf1”中的结果为0而不是12。原因是什么,我该如何解决?

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. 这是因为当您使用tolist()将其转换为列表时,会得到列表的子集。 Meaning this is your x : 表示这是您的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] . 为了使countOf1正常工作,您需要针对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. 请记住,numpy矩阵就像一个列表列表。 Even though you only created one row vector, numpy writes it with 2 brackets ([[0,1,2,3,4...,11]]). 即使您只创建了一个行向量,numpy还是用2个方括号([[0,1,2,3,4 ...,11]])编写了它。 So when you changed it to a list with tolist(), you created a list within a list. 因此,当您使用tolist()将其更改为列表时,便在列表中创建了一个列表。 Since the list within the list != 1, the count is 0. 由于列表中的列表!= 1,因此计数为0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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