如何在Python中每行显示16个值?

2024-04-26 00:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python程序,我想将数据写入一个文件,使每行有16个值。请问我该怎么做?你知道吗


Tags: 文件数据程序个值
2条回答

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

可以使用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)

相关问题 更多 >