如何将Python列表格式化为初始化的C数组?

如何将Python列表格式化为初始化的C数组?,python,c,lookup-tables,Python,C,Lookup Tables,我需要为用C编写的嵌入式固件生成一个查找表。用Python生成值很容易,但是如何以C编译器可以接受的形式输出这些值 例如,我想要这样的东西: >>> a = range(0,20) >>> print(to_c_array(a)) int table[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; 这里有一个函数可以满足您的要求:

我需要为用C编写的嵌入式固件生成一个查找表。用Python生成值很容易,但是如何以C编译器可以接受的形式输出这些值

例如,我想要这样的东西:

>>> a = range(0,20)
>>> print(to_c_array(a))
int table[] = {
    0, 1, 2, 3, 4, 5, 6, 7,
    8, 9, 10, 11, 12, 13, 14, 15,
    16, 17, 18, 19};

这里有一个函数可以满足您的要求:

def to_c_array(values, ctype="float", name="table", formatter=str, colcount=8):
    # apply formatting to each element
    values = [formatter(v) for v in values]

    # split into rows with up to `colcount` elements per row
    rows = [values[i:i+colcount] for i in range(0, len(values), colcount)]

    # separate elements with commas, separate rows with newlines
    body = ',\n    '.join([', '.join(r) for r in rows])

    # assemble components into the complete string
    return '{} {}[] = {{\n    {}}};'.format(ctype, name, body)
。。。以及如何使用它生成伽马校正的示例 查找表:

>>> gamma = 0.3
>>> N = 32
>>> values = [math.pow(float(i)/N, gamma) for i in range(N)]
>>> print(to_c_array(values, ctype='float', name='gamma', formatter=lambda x: '{:0.5f}'.format(x)))
float gamma[] = {
    0.00000, 0.35355, 0.43528, 0.49158, 0.53589, 0.57299, 0.60520, 0.63385,
    0.65975, 0.68348, 0.70543, 0.72589, 0.74509, 0.76320, 0.78036, 0.79668,
    0.81225, 0.82716, 0.84147, 0.85523, 0.86849, 0.88129, 0.89368, 0.90568,
    0.91731, 0.92862, 0.93961, 0.95031, 0.96073, 0.97090, 0.98082, 0.99052};