将int转换为二进制并返回其数字的总和

时间:2018-02-13 12:59:57

标签: python python-3.x

我正在尝试将整数转换为二进制值,然后打印出其数字的总和。 我的代码如下:

number = 30                    # declare int
binary_number = "{0:b}".format(number)        # convert into binary
# print(binary_number) gives output of 11110 

print(sum(int(item) for item in binary_number ))     # print out the sum of 
digits
# works and gives gives an output of 4 (1+1+1+1+0)

但是当我尝试用另一种方式表达逻辑时,它会出错,我无法理解为什么:

for item in binary_number:
   print(sum(int(item)))

# output is error:
#Type Error: 'int' object is not iterable

提前感谢您的帮助! 问候, 安迪

3 个答案:

答案 0 :(得分:0)

你的改述改变了

的语义
print the sum of the elements of a list

for the elements in this list print the sum of each single item.

答案 1 :(得分:0)

将二进制数映射到整数并对它们求和将得到所需的结果。

sum(map(int,"{0:b}".format(number)))

答案 2 :(得分:0)

此表达式

int(item) for item in binary_number

提供可互换的,这就是sum(int(item) for item in binary_number)有效的原因。

这些行

for item in binary_number:
   print(sum(int(item)))

item连续设置为"1" "1" "1" "1" "0",并在循环内部使用sum(int(item))解析到sum(1)sum(0)。现在你明白为什么sum()不符合你的期望吗?正如错误消息所示,'int'对象不可迭代。由于您没有可迭代,您需要自己进行求和:

total = 0
for item in binary_number:
   total += int(item)
print(total)