【问题标题】:Modifying this simple array creation function on a more Pythonic way以更 Pythonic 的方式修改这个简单的数组创建函数
【发布时间】:2015-12-29 03:30:13
【问题描述】:

我有以下函数,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

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

【问题讨论】:

  • 输入总是整数吗?
  • 是的,总是整数。

标签: python arrays list python-2.7


【解决方案1】:

既然你说输入总是整数(根据 cmets)。您可以为此使用单行列表推导。示例 -

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

【讨论】:

  • 正是我想要的。非常感谢,阿南德。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-11
  • 2011-04-20
  • 1970-01-01
  • 2017-07-09
  • 2014-09-17
  • 1970-01-01
相关资源
最近更新 更多