这里有一个功能可以满足您的要求:
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};