【问题标题】:Index out of range error, python 3.5. Only happens in 'while' loop索引超出范围错误,python 3.5。只发生在'while'循环中
【发布时间】:2015-12-30 01:35:27
【问题描述】:

在为我的朋友编写二进制转换程序时,我在使用X[N] = Y 命令时不断收到索引超出范围错误,其中X 是一个列表,N 是索引号是列表(由变量名为 Bit) 和 Y 是我分配给列表 X 中索引 N 中的变量的值。

好吧,我应该只输入代码并进行解释,但基本上是说索引超出范围,而代码 Numbers[Bit] = 0Number[Bit] = 1 在 while 循环内,但它在代码中的其他任何地方都有效。变量 Bit 等于整数 7,列表 Numbers 包含变量 abcdefg 和 @987654分开的意思是有 0-7 个索引。我尝试将Bit 值设为 0,但这也不起作用。但是,只要将 Numbers[Bit] 代码段放在 while 循环之外,代码就可以正常工作。有什么想法吗?

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0

def loop():
    Bit = 7
    Numbers = [a, b, c, d, e, f, g, h];
    Num = 128
    Input = int(input("What Number do you want to convert?" ))

    while Input > 0:
        if Input > Num:
            Input = Input - Num
            Numbers[Bit] = 1
        else:
            Numbers[Bit] = 0

        Bit = Bit - 1
        Num = Num/2
    Numbers = str(Numbers)
    print (Numbers)

loop()

【问题讨论】:

  • 最初设置为 7。
  • Num/2 没有使用整数除法,而是使用真除法。你最终会得到分数,而不是 0。这不是问题的全部,但它没有帮助。

标签: python loops while-loop indexoutofboundsexception python-3.5


【解决方案1】:

您正在与Input > Num 进行比较,应该是Input >= Num

要以正确的顺序获取位,您可以使用:

def loop():
    number = int(input("What Number do you want to convert?" ))
    bits = [(number>>b) & 1 for b in range(7,-1,-1)]
    print(bits)

【讨论】:

  • Num 也变成了分数。
  • 谢谢!这解决了这个问题,虽然我意识到这个列表对于二进制来说是错误的,但是很有帮助。
猜你喜欢
  • 1970-01-01
  • 2019-07-27
  • 2013-03-09
  • 2021-09-02
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多