Avi*_*ión 2 python arrays list python-2.7
我有以下函数,createFreeSpaces(first_byte, last_byte)它输入两个数字first_byte和last_byte(总是整数),并创建一个列表,其中包含特定格式的这两个数字之间的数字.这很容易,但我有点难以解释,所以让我们看看我的尝试和一个例子.
例:
createFreeSpaces(4, 7)
输出:
555555 0 0 "FREE: [5.0]"
555555 0 0 "FREE: [5.1]"
555555 0 0 "FREE: [5.2]"
555555 0 0 "FREE: [5.3]"
555555 0 0 "FREE: [5.4]"
555555 0 0 "FREE: [5.5]"
555555 0 0 "FREE: [5.6]"
555555 0 0 "FREE: [5.7]"
555555 0 0 "FREE: [6.0]"
555555 0 0 "FREE: [6.1]"
555555 0 0 "FREE: [6.2]"
555555 0 0 "FREE: [6.3]"
555555 0 0 "FREE: [6.4]"
555555 0 0 "FREE: [6.5]"
555555 0 0 "FREE: [6.6]"
555555 0 0 "FREE: [6.7]"
Run Code Online (Sandbox Code Playgroud)
这是我的尝试,因为你可以看到它似乎有点脏,而不是Pythonic.
def createFreeSpaces(first_byte, last_byte):
start_bit = 0
end_bit = 7
b_start = first_byte + 1
b_end = last_byte
b_diff = b_end - b_start
h = 0
final_list = []
while h < b_diff * 8:
if start_bit == 8:
start_bit = 0
b_start = b_start + 1
final_list.append('555555 0 0 "FREE: [' + str(b_start) + '.' + str(start_bit) + ']"')
s_start = b_start + 1
start_bit = start_bit + 1
h = h + 1
return final_list
Run Code Online (Sandbox Code Playgroud)
我正在清理我的代码所以我想知道是否有人可以帮助我并告诉我如何以更加pythonic的方式制作这个简单的功能?
既然你说输入总是整数(根据评论).您可以使用单行列表解析.示例 -
def createFreeSpaces(first_byte, last_byte):
return ['555555 0 0 "FREE: [{}.{}]"'.format(x,y) for x in range(first_byte + 1, last_byte) for y in range(8)]
Run Code Online (Sandbox Code Playgroud)
使列表理解线变得更小 -
def createFreeSpaces(fbyte, lbyte):
fmt = '555555 0 0 "FREE: [{}.{}]"'
return [fmt.format(x,y) for x in range(fbyte + 1, lbyte) for y in range(8)]
Run Code Online (Sandbox Code Playgroud)
演示 -
>>> def createFreeSpacesNew(first_byte, last_byte):
... return ['555555 0 0 "FREE: [{}.{}]"'.format(x,y) for x in range(first_byte + 1, last_byte) for y in range(8)]
...
>>> pprint.pprint(createFreeSpacesNew(4,7))
['555555 0 0 "FREE: [5.0]"',
'555555 0 0 "FREE: [5.1]"',
'555555 0 0 "FREE: [5.2]"',
'555555 0 0 "FREE: [5.3]"',
'555555 0 0 "FREE: [5.4]"',
'555555 0 0 "FREE: [5.5]"',
'555555 0 0 "FREE: [5.6]"',
'555555 0 0 "FREE: [5.7]"',
'555555 0 0 "FREE: [6.0]"',
'555555 0 0 "FREE: [6.1]"',
'555555 0 0 "FREE: [6.2]"',
'555555 0 0 "FREE: [6.3]"',
'555555 0 0 "FREE: [6.4]"',
'555555 0 0 "FREE: [6.5]"',
'555555 0 0 "FREE: [6.6]"',
'555555 0 0 "FREE: [6.7]"']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |