在 python 3 中的列表中查找组号的二进制形式的 1 的总数
Find the the total number of 1's in binary form for a group number's in a list in python 3
我想计算列表中数字的二进制格式“1”的总数。
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
输出为0。
而所需的输出应采用 [3,3]
的形式
这是 Z 包含的每个元素中的个数:
z = ['0b111000','0b1000011']
d = z.count('1')
这将尝试查找字符串 '1'
在 z
中出现的次数。这显然 returns 0
因为 z
包含 '0b111000'
和 '0b1000011'
.
您应该遍历 z
中的每个字符串并计算每个字符串中 '1'
的数量:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
这里是:
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
您的代码存在问题,您试图在列表类型上使用 count() 方法并且它用于字符串。您首先需要从列表中获取字符串,然后对其使用 count() 方法。
希望对您有所帮助:)
list.count(x) 将计算出现的次数,因此它只计算等于 x 的元素。
使用列表推导式遍历每个字符串,然后然后计算 1 的数量。如:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
这将输出:
[3, 3]
我想计算列表中数字的二进制格式“1”的总数。
z = ['0b111000','0b1000011'] # z is a list
d = z.count('1')
print(d)
输出为0。
而所需的输出应采用 [3,3]
的形式这是 Z 包含的每个元素中的个数:
z = ['0b111000','0b1000011']
d = z.count('1')
这将尝试查找字符串 '1'
在 z
中出现的次数。这显然 returns 0
因为 z
包含 '0b111000'
和 '0b1000011'
.
您应该遍历 z
中的每个字符串并计算每个字符串中 '1'
的数量:
z = ['0b111000','0b1000011']
output = [string.count('1') for string in z]
print(output)
# [3, 3]
这里是:
z=['0b111000','0b1000011']
finalData = []
for word in z:
finalData.append(word.count('1'))
print(finalData)
您的代码存在问题,您试图在列表类型上使用 count() 方法并且它用于字符串。您首先需要从列表中获取字符串,然后对其使用 count() 方法。
希望对您有所帮助:)
list.count(x) 将计算出现的次数,因此它只计算等于 x 的元素。
使用列表推导式遍历每个字符串,然后然后计算 1 的数量。如:
z = ['0b111000','0b1000011']
d = [x.count("1") for x in z]
print(d)
这将输出:
[3, 3]