計算機科学のブログ

Python - List of Files: Functions, Modules and Files - if statement

Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly GuidePaul Barry(著)、 O’Reilly Mediaの Chapter 3.(List of Files: Functions, Modules and Files)、SHARPEN YOUR PENCIL(74/108)の解答を求めてみる。

Jupyter(コード、入出力結果)

Files.ipynb

def read_swim_data(filename):
    swimmer, age, distance, stroke = filename.removesuffix('.txt').split('-')
    with open(FOLDER + filename) as file:
        lines = file.readlines()
    times = lines[0].rstrip('\n').split(',')
    converts = []
    for t in times:
        # ここから
        minutes, rest = t.split(':')
        seconds, hundredths = rest.split('.')
        converted_time = (
            int(minutes) * 60 * 100 + int(seconds) * 100 + int(hundredths)
        )
        converts.append(converted_time)
        # ここまで
    average = statistics.mean(converts)
    mins_secs, hundredths = str(round(average / 100, 2)).split('.')
    mins_secs = int(mins_secs)
    minutes = mins_secs // 60
    seconds = mins_secs - minutes * 60
    average = f'{minutes}:{seconds}.{hundredths}'
    return (
        swimmer,
        age,
        distance,
        stroke,
        times,
        average,
    )
for filename in swim_files:
    print(filename)
    print(read_swim_data(filename))
Hannah-13-100m-Free.txt
('Hannah', '13', '100m', 'Free', ['1:21.43', '1:21.40', '1:21.62', '1:25.38'], '1:22.46')
Darius-13-100m-Back.txt
('Darius', '13', '100m', 'Back', ['1:22.57', '1:29.64', '1:20.39', '1:23.83'], '1:24.11')
Owen-15-100m-Free.txt
('Owen', '15', '100m', 'Free', ['1:15.57', '1:14.40', '1:19.82', '1:12.90'], '1:15.67')
Mike-15-100m-Free.txt
('Mike', '15', '100m', 'Free', ['1:02.52', '1:02.56', '1:06.41', '1:07.08', '1:02.56', '1:03.23', '1:04.54'], '1:4.13')
Hannah-13-100m-Back.txt
('Hannah', '13', '100m', 'Back', ['1:35.75', '1:32.78', '1:34.01', '1:32.57'], '1:33.78')
Mike-15-100m-Back.txt
('Mike', '15', '100m', 'Back', ['1:19.23', '1:13.70', '1:13.96', '1:15.94'], '1:15.71')
Mike-15-100m-Fly.txt
('Mike', '15', '100m', 'Fly', ['1:14.55', '1:14.15', '1:08.38', '1:08.74', '1:10.89', '1:09.47', '1:09.52', '1:09.86', '1:09.83'], '1:10.6')
Abi-10-50m-Back.txt



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In[110], line 3
      1 for filename in swim_files:
      2     print(filename)
----> 3     print(read_swim_data(filename))


Cell In[109], line 9, in read_swim_data(filename)
      6 converts = []
      7 for t in times:
      8     # ここから
----> 9     minutes, rest = t.split(':')
     10     seconds, hundredths = rest.split('.')
     11     converted_time = (
     12         int(minutes) * 60 * 100 + int(seconds) * 100 + int(hundredths)
     13     )


ValueError: not enough values to unpack (expected 2, got 1)