如何计算Python中的零数?

时间:2014-01-04 05:49:22

标签: list python-2.7 count

我的代码目前写为:

convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1}
rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
numgood = 25 - rows.count(0)

print numgood
>> 25

它总是以25为单位,所以不只是行不包含0。

3 个答案:

答案 0 :(得分:3)

您打印过rows吗?

它是[[0, 1, 0, 0, 2], [1, 2, 0, 1, 2], [3, 1, 1, 1, 1], [1, 0, 0, 1, 0], [0, 3, 2, 0, 1]],所以你有一个嵌套列表。

如果您想计算这些嵌套列表中0的数量,可以尝试:

import random

convert = {0:0, 1:1, 2:2, 3:3, 4:0, 5:1, 6:2, 7:1}
rows = [[convert[random.randint(0, 7)] for _ in range(5)] for _ in range(5)]

numgood = 25 - sum(e.count(0) for e in rows)
print numgood

<强>输出:

18

答案 1 :(得分:2)

rows不包含任何零;它包含列表,而不是整数。

>>> row = [1,2,3]
>>> type(row)
<type 'list'>
>>> row.count(2)
1
>>> rows = [[1,2,3],[4,5,6]]
>>> rows.count(2)
0
>>> rows.count([1,2,3])
1

要计算行中任何列表中的零个数,可以使用生成器表达式:

>>> rows = [[1,2,3],[4,5,6], [0,0,8]]
>>> sum(x == 0 for row in rows for x in row)
2

答案 2 :(得分:0)

您还可以使用numpy:

import numpy as np
import random

convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1}
rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
numgood = 25 - np.count_nonzero(rows)

print numgood

输出:

9