如何在Python的每一行上显示16个值?

时间:2018-11-04 22:06:16

标签: python formatting

我正在编写一个Python程序,我想将我的数据写到文件中,使得每行有16个值。我该怎么做?

2 个答案:

答案 0 :(得分:0)

您只需每16个元素添加一个字符'\n'(换行符)。 您可以通过迭代数据轻松地做到这一点。

答案 1 :(得分:0)

您可以使用Python的列表切片。参见here if you are unfamiliar。本质上,您希望一个“滑动窗口”宽16个元素。

一种解决方案:

# create list [1 ... 999] ... we will pretend this is your input data
data = range(1, 1000)

def write_data(filename, data, per_line=16):
    with open(filename, "w+") as f:
        # get number of lines
        iterations = (len(data) / per_line) + 1

        for i in range(0, iterations):
            # 0 on first iteration, 16 on second etc.
            start_index = i * per_line
            # 16 on first iteration, 32 on second etc.
            end_index = (i + 1) * per_line
            # iterate over data 16 elements at a time, from start_index to end_index
            line = [str(i) for i in data[start_index:end_index]]
            # write to file as comma seperated values
            f.write(", ".join(line) + " \n")

# call our function, we can specify a third argument if we wish to change amount per line
write_data("output.txt", data)