以更Pythonic的方式修改这个简单的数组创建函数

时间:2015-10-01 07:11:03

标签: python arrays list python-2.7

我有以下函数,createFreeSpaces(first_byte, last_byte)输入两个数字first_bytelast_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]"

这是我的尝试,因为你可以看到它看起来有点脏,而不是 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

我正在清理我的代码,所以我想知道是否有人可以帮助我并告诉我如何以更加pythonic的方式制作这个简单的功能?

1 个答案:

答案 0 :(得分:6)

因为您说输入将始终为整数(根据注释)。您可以使用单行列表理解。示例 -

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)]

使列表理解线变得更小 -

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)]

演示 -

>>> 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]"']