从我创建的列表中只提取一个元素

2024-04-24 10:32:03 发布

您现在位置:Python中文网/ 问答频道 /正文

议程:

简单地说,我想把二进制数改成十进制数,我知道Python有实现这个目标的内置函数,但我想用代码手动实现

问题:

我陷入了从用长度用户输入创建的列表中提取元素的困境,它只从我用长度用户输入创建的列表中给我一个值

我的代码:

user_input = int(input("Enter the binary number "))
change_user_input_to_list = [int(x) for x in str(user_input) ]
# print(type(change_user_input_to_list))
# print(len(change_user_input_to_list))
length_of_user_input = len(change_user_input_to_list)
list_created_with_length_of_user_input = []

for i in range(length_of_user_input):
    calculation_for_making_list_with_length_of_user_input = 2**i
    list_created_with_length_of_user_input.append(calculation_for_making_list_with_length_of_user_input)

print(list_created_with_length_of_user_input)
result =0
coun = 0

#problem is here

while coun <length_of_user_input:
    if list_created_with_length_of_user_input[coun]==1:
        print(list_created_with_length_of_user_input[coun])
    coun= coun+1

print(result)

Tags: ofto代码用户列表forinputwith
2条回答

我们需要检查if change_user_input_to_list[coun]==1:,而不是if list_created_with_length_of_user_input[coun]==1:。你知道吗

更改最少的代码:

user_input = int(input("Enter the binary number "))
change_user_input_to_list = [int(x) for x in str(user_input) ]
length_of_user_input = len(change_user_input_to_list)
list_created_with_length_of_user_input = []

for i in range(length_of_user_input):
    calculation_for_making_list_with_length_of_user_input = 2**i
    list_created_with_length_of_user_input.append(calculation_for_making_list_with_length_of_user_input)

result =0
coun = 0

while coun <length_of_user_input:
    if change_user_input_to_list[coun]==1:
        result += list_created_with_length_of_user_input[coun]
    coun= coun+1

print(result)

注:

如果输入是10111,那么代码将把反向二进制数11101转换成十进制数29。你知道吗

b_num = list(input("Enter the binary number "))
value = 0

for i in range(len(b_num)):
    digit = b_num.pop()
    if digit == '1':
        value = value + pow(2, i)
print("The decimal value of the number is", value)

这是将二进制转换成十进制的最简单方法,希望它能像您期望的那样工作

相关问题 更多 >