首页 > 解决方案 > 十进制到二进制转换的列表理解中的 if/else

问题描述

我确实阅读了相关答案,但仍然无法弄清楚如何正确地进行列表理解。

我编写了将二进制转换为十进制和其他方式的函数,但是在我的十进制到二进制转换中,我想使用列表理解而不是我现在使用的循环,但我无法弄清楚如何正确编写它。

我的代码如下:

from math import log

def dec_to_binary(n: int) -> str:
    """Convert integer to binary."""
    indices = []
    
    while n > 0:
        index = int(log(n, 2))
        indices.append(index)
        n -= 2**index
    binary = ['0' for x in range(max(indices)+1)]
    
    for i in indices:
        binary[i] = '1'
        
    binary = binary[::-1]
    binary = ''.join(binary)
    return binary

在这里,我重复计算一个数字的 log(2) 以获得索引,该索引将在最终二进制数中变为 1。之后,我创建一个长度等于最高日志值的零列表,然后在相应的索引中将“0”替换为“1”。

这工作正常,但我试图看看我是否可以一次完成所有工作,但到目前为止我想出的似乎不起作用:

binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']

解释器一直在else声明中指出错误。

binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']
  File "<ipython-input-297-3da1307fffd5>", line 1
    binary = ['0' for x in range(max(indices)+1) if x not in indices else '1']
                                                                      ^
SyntaxError: invalid syntax

我怎样才能正确地重写它?

标签: pythonlist-comprehension

解决方案


将 if/else 放在前面

binary = ['0' if x not in indices else '1' for x in range(max(indices)+1)]

推荐阅读