Python导出到Cs

2024-05-19 02:14:05 发布

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

这是我正在使用的data(示例):

('Bouwmeester', [(0, 37), (155, 194), (327, 420), (541, 602), (654, 717), (761, 834), (1001, 1052), (0, 27), (79, 119), (405, 460), (546, 624), (750, 798), (834, 897), (1061, 1139), (0, 33), (170, 204), (289, 328), (447, 498), (575, 576), (729, 766), (962, 995), (1073, 1113), (1163, 1200)])
('Schwartz', [(0, 40), (165, 209), (362, 417), (550, 567), (761, 809), (881, 954), (1052, 1113), (27, 54), (195, 295), (482, 546), (707, 757), (906, 1003), (1080, 1126), (0, 33), (145, 229), (353, 408), (492, 561), (576, 640), (736, 766), (820, 870), (1094, 1163)])
('Foligno', [(0, 40), (176, 209), (362, 416), (552, 567), (761, 835), (883, 954), (459, 502), (546, 583), (757, 826), (1189, 1200), (0, 33), (212, 249), (353, 413), (575, 576), (696, 722), (722, 762)])

以下是我到目前为止的Script

^{pr2}$

输出:

Player  Shift1
Dumba   (39, 39)

output是最后一个数据,而不是整个文件。另外,我希望所有的转移到output,在那里有自己的cellExample:

Player        Shift1       Shift2      Shift3       Shift4
Bouwmeester   (0, 37)    (155, 194)  (327, 420)   (541, 602)

Tags: 文件数据示例outputdataexamplescriptcell
2条回答

您需要为每一行调用writerow,这对每个玩家来说是一次。您可以在循环中执行以下操作:

with open('Shiftdata.csv', 'w') as out:
    writer = csv.writer(out)
    header_cells = ["Player"]
    number_of_shifts = 10
    for shift_num in range(1, number_of_shifts + 1):
        header_cells.append("Shift{}".format(shift_num))
    writer.writerow(header_cells)
    for player, shifts in players.items():
        cells = [player]
        cells.extend(shifts)
        writer.writerow(cells)

唯一的问题是你写了一行后的标题:

writer.writerow([name, times])

相反,您需要编写每个行数据,这可以在第二个for循环中完成。在

您还需要通过找到player times列表的max length来计算出有多少Shift#列。这可以通过使用循环或内置的max函数来实现:

^{pr2}$

把这两者结合起来:

# Move the file prep above the loop
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)

shift_count = max(
    len(shift_times) for shift_times in players.values()
)

shift_cols = [
    "Shift{}".format(num) for num in range(1, shift_count + 1)
]

writer.writerow(["Player"] + shift_cols)

for t in players.items():
    print(t)

    row = [
        t[0],  # the first column is the player's name
    ]
    row += t[1]  # then all of the shift times next to it

    writer.writerow(row)

outfile.close()

相关问题 更多 >

    热门问题