这是我正在使用的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
:import csv
from itertools import combinations, product
#Header = LastName StartTime EndTime Duration Period TeamAbbrev Position
#Import Game
with open('2017020397.csv', newline='') as f:
next(f)
skaters = '\n'.join(' '.join(row) for row in csv.reader(f))
data = skaters.splitlines()
def to_secs(ms):
''' Convert a mm:ss string to seconds '''
m, s = map(int, ms.split(':'))
return 60 * m + s
# Store a list of (start, end) times for each player
players = {}
for row in data:
name, start, end = row.split(None, 3)[:3]
times = to_secs(start), to_secs(end)
players.setdefault(name, []).append(times)
for t in players.items():
print(t)
outfile = open("ShiftData.csv","a",newline='')
writer = csv.writer(outfile)
writer.writerow(["Player","Shift1"])
writer.writerow([name, times])
outfile.close()
输出:
Player Shift1
Dumba (39, 39)
output
是最后一个数据,而不是整个文件。我也想在自己的output
中将所有转移到cell
。 Example:
Player Shift1 Shift2 Shift3 Shift4
Bouwmeester (0, 37) (155, 194) (327, 420) (541, 602)
最佳答案
主要问题是您仅在标头之后写一行:
writer.writerow([name, times])
相反,您需要写入数据的每一行,您可以在第二个for循环中执行此操作。
您还需要通过找到玩家时间列表的最大长度来计算出多少
Shift#
列。只需使用循环或内置的max
函数即可完成此操作:# the loop way
shift_count = 0
for times in players.values():
if len(times) > shift_count:
shift_count = len(times)
# the quicker built-in way
shift_count = max(
len(shift_times) for shift_times in players.values()
)
# then make the column names
shift_cols = [
"Shift{}".format(num) for num in range(1, shift_count + 1)
]
将这两个放在一起:
# 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()