简体   繁体   English

列表理解最佳实践

[英]List Comprehension Best Practice

I'm very very new to python and I'm writing a compiler program for assembly.我对python非常陌生,我正在编写一个用于汇编的编译器程序。

An example line of assembly code would be:汇编代码的示例行是:

@2

The resulting line of machine code with should be 16 bits long, with the msb being '0' to represent '@', and the remaining 15 bits being a binary representation of the decimal following the '@'.生成的机器代码行应为 16 位长,msb 为 '0' 表示 '@',其余 15 位是 '@' 后面十进制的二进制表示。 Each instruction has already been broken down and correctly formatted into a list.每条指令都已被分解并正确格式化为一个列表。

Currently I am doing the conversion as follow:目前我正在按如下方式进行转换:

rmw = ['0'+f"{int(x[1:]):b}".zfill(15) if x.startswith('@') else x for x in rmw]

This works great, but seems a little bit clunky to me, is this best practice?这很好用,但对我来说似乎有点笨拙,这是最佳实践吗? I think I could probably set zfill to 16, but would rather keep the two parts separate then combine them I think.我想我可以将 zfill 设置为 16,但我认为宁愿将两个部分分开然后将它们组合起来。 My background is C programming so this is a bit of a departure.我的背景是 C 编程,所以这有点偏离。

It seems perfectly fine to me.对我来说似乎完全没问题。 However, there are two simplifications you can make to shorten it:但是,您可以通过两种简化方式来缩短它:

  1. Include the leading 0 in the f-string so the ugly '0'+ can be excluded.在 f 字符串中包含前导0 ,因此可以排除丑陋的'0'+
  2. Take advantage of string formatting to pad with zeros directly in the f-string (with 015 ) , avoiding the extra zfill .利用字符串格式直接在 f 字符串中填充零(使用015 ),避免额外的zfill
rmw = [f"0{int(x[1:]):015b}" if x.startswith('@') else x for x in rmw]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM