python - 十进制到二进制转换的列表理解中的 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
我怎样才能正确地重写它?
解决方案
将 if/else 放在前面
binary = ['0' if x not in indices else '1' for x in range(max(indices)+1)]
推荐阅读
- html - 为什么即使我根本没有触摸该配置,我的视频也不会在 Safari 上播放任何声音?
- highcharts - 在 Ionic 4 中使用 css 自定义 highcharts
- linux - 如何仅打印存在相同文件名的文件夹名称
- python - 如何根据python字典的键和值有条件地将数据添加到Excel文件中的列中,同时保持其他列一致
- mysql - 如何创建获取值表单表并更新不同表的触发器
- r - 如何在开发的图形用户界面 (GUI) 中显示“R 控制台内容”
- ruby-on-rails - 选择字段以在更新时创建或更新 has_many 记录
- java - 如何解决此问题:尝试在空对象引用上调用虚拟方法 'android.text.Editable android.widget.EditText.getText()'
- qt - 在 qtcreator 调试器中发送 gdb 命令
- python-3.x - 使用来自 win32com.client 'SAPI.Spvoice' 的调度