将列表列表的每个元素从 Python 输出到 .csv 文件

Output each element of list of list from Python to .csv file

我正在尝试将 Python 中列表列表中的每个 list-element 写入 .csv 文件,但我一直在获取字母为space-由于某些未知原因分开。示例代码如下:

import xlsxwriter

S = [[1, 7, 8, 0], [4, 5, 7, 3], [2, 9, 10, 11, 6]]

with open('S_N=6.csv', 'wt') as graph:

    graphWriter = csv.writer(graph, delimiter = ' ')

    for x in range(len(S)):

      graphWriter.writerow('set S' + str(x+1)  + ':=')

我的预期输出(注意 S[i] 中的 index i 可以计算为(每个 list/3) + 1)

set S[1] = 1 7 8
set S[2] = 4 5 7
set S[3] = 2 9 10 11

有人可以帮我解决这个问题吗?任何输入将不胜感激。

您的输出文件不是 CSV 文件。使用 CSV 编写器生成它是没有意义的。就是一堆行,就写一堆吧。

S = [[1, 7, 8, 0], [4, 5, 7, 3], [2, 9, 10, 11, 6]]

with open('S_N=6.csv', 'w') as fp:
    for x in S:
        *items, idx = x
        idx = int(idx / 3 + 1)
        items = ' '.join(map(str, items))
        fp.write(f'set S[{idx}] = {items}\n')
  • *items, idx = xx 中除最后一个列表元素之外的所有元素分配给 items,并将最后一个元素分配给 idx.
  • idx / 3 + 1returns一个float,即1.0等等。它必须显式转换为 int
  • f'...'是格式化字符串,可以在花括号里面用Python表达式。

这里写道:

set S[1] = 1 7 8
set S[2] = 4 5 7
set S[3] = 2 9 10 11

由于格式字符串可以包含复杂的表达式,如果你真的想,你可以这样写:

for x in S:
    *items, idx = x
    fp.write(f'set S[{int(idx / 3 + 1)}] = {' '.join(map(str, items))}\n')

你可以这样做:

S = [[1, 7, 8, 0], [4, 5, 7, 3], [2, 9, 10, 11, 6]]
with open('S_N=6.csv', 'w+') as f:
    for x in S:
        f.write('set S[' + str((int(x[-1]/3))+1) + '] = ' + ' '.join(str(a) for a in x[:-1]) + '\n')

它将写入文件 S_N=6.csv 以下输出:

set S[1] = 1 7 8
set S[2] = 4 5 7
set S[3] = 2 9 10 11