📚 Practical Programming Techniques | 实用编程技术(体育数据分析应用)
In modern physical education and sports science, coaches and analysts increasingly rely on programming to collect performance data, spot patterns, and make evidence-based decisions. This article introduces practical programming techniques that can be applied to sports contexts, from recording match statistics to visualising fitness trends.
在现代体育与运动科学中,教练和分析师越来越多地依靠编程来收集表现数据、发现规律并做出循证决策。本文介绍可应用于体育场景的实用编程技术,从记录比赛数据到可视化体能趋势。
1. Algorithmic Thinking and Problem Decomposition | 算法思维与问题分解
Before writing any code, a programmer should break a sports problem into small, manageable steps. For example, calculating a sprinter's average speed over 100 m requires input, processing, and output stages. The same logic applies to more complex tasks such as ranking players by pass completion rate or identifying the highest heart-rate zone in a training session.
在编写任何代码之前,程序员应把一个体育问题分解为若干个可操作的小步骤。例如,计算短跑运动员 100 米的平均速度需要输入、处理和输出三个阶段。同样的逻辑也适用于更复杂的任务,比如按传球成功率对球员排名,或找出训练课中最高心率区间。
Each stage should be written in plain English or pseudocode before translating it into a programming language. This reduces logical errors and makes the solution easier to test. For the sprint example, the algorithm is: store the distance, store the time, divide distance by time, and display the result.
每个阶段都应先用简单英语或伪代码写出,再翻译成编程语言。这能减少逻辑错误,并使解决方案更容易测试。对于短跑示例,算法是:存储距离、存储时间、用距离除以时间,然后显示结果。
v = s ÷ t
Here, v is average speed, s is distance, and t is time. Keeping the formula as a separate step helps you verify that the units are consistent before coding.
此处 v 是平均速度,s 是距离,t 是时间。把公式作为独立步骤有助于在编码前检查单位是否一致。
2. Variables, Data Types and Unit Consistency | 变量、数据类型与单位一致性
In sports analytics, different types of data require different programming data types. A player's name is a string, a score or time is usually an integer or float, and a true/false flag such as 'selected for squad' is a Boolean. Choosing the correct data type prevents unexpected calculation errors.
在体育数据分析中,不同类型的数据需要不同的编程数据类型。球员姓名是字符串,得分或时间通常是整数或浮点数,而“是否入选名单”这样的真/假标记是布尔值。选择正确的数据类型可以防止意外的计算错误。
Unit consistency is equally important. If distance is recorded in metres and time in seconds, the speed will naturally be in metres per second. Mixing kilometres and metres without conversion is a common source of error. Use clear variable names to make units explicit:
单位一致性同样重要。如果距离以米为单位、时间以秒为单位,速度自然以米/秒为单位。不进行换算就混用千米和米是常见的错误来源。使用清晰的变量名可以明确单位:
distance_m = 100
time_s = 12.4
speed_ms = distance_m / time_s
ly what units are being used. This technique is especially useful when the same dataset contains heart rates, body mass, and distances in different systems.
变量名以 _m、_s 和 _ms 结尾,这样读者可以立即知道使用了什么单位。当同一数据集包含不同体系的心率、体重和距离时,这种技术尤其有用。
3. Selection and Repetition for Match Analysis | 选择与循环在比赛分析中的应用
Conditional statements and loops are the backbone of match analysis scripts. A loop can iterate through every player in a squad, while an if statement can apply a decision rule, such as flagging a player whose heart rate exceeds a training threshold.
条件语句和循环是比赛分析脚本的基础。循环可以遍历球队中的每个球员,而 if 语句可以应用决策规则,例如标记心率超过训练阈值的球员。
for each player in squad:
if heart_rate > 180:
mark as high intensity
This simple structure can be extended to count the number of high-intensity efforts, calculate the percentage of time spent in each heart-rate zone, or compare substitutes with starters. Repetition avoids writing nearly identical code many times.
这个简单的结构可以扩展为统计高强度运动的次数、计算每个心率区间所占时间百分比,或比较替补球员与首发球员。循环可以避免多次编写几乎相同的代码。
When processing a match, you might also use a while loop to keep reading data until the final whistle event appears. Conditional statements then decide what to do with each event, such as a shot, foul, or substitution, making the program fully data-driven.
在处理比赛时,你可能还会使用 while 循环不断读取数据,直到出现终场哨事件。然后条件语句决定如何处理每个事件,比如射门、犯规或换人,使程序完全由数据驱动。
4. Functions and Modular Coding | 函数与模块化编码
A function is a reusable block of code that performs one clear task. In sports programming, a function might calculate body mass index (BMI), convert pace to speed, or compute a player's efficiency rating. Using functions avoids duplication and makes testing much easier.
函数是一个可重复使用的代码块,用于执行一项明确的任务。在体育编程中,函数可以计算身体质量指数(BMI)、将配速转换为速度,或计算球员的效率评分。使用函数可以避免重复,并使测试更加容易。
function calculate_bmi(weight_kg, height_m):
return weight_kg ÷ height_m²
The formula above uses height in metres squared. If the input height is given in centimetres, a conversion must be performed first. Encapsulating the conversion inside the function keeps the main program clean and prevents inconsistent units.
上述公式用身高(米)的平方。如果输入身高以厘米为单位,则必须先进行换算。把换算封装在函数内部,可以保持主程序简洁,防止单位不一致。
can each be tested independently, which is a key practical technique for larger projects.
模块化编码还意味着将输入、处理和输出分离到不同的函数中。例如,load_match_data()、calculate_team_stats() 和 display_summary() 可以分别独立测试,这是较大项目中关键的实用技术。
5. Lists and Arrays for Squad Data | 用于阵容数据的列表与数组
Lists and arrays store ordered collections of data, such as the 20 m sprint times of every player in an academy squad. A list allows you to access individual values by index, loop through them, and compute summary statistics quickly.
列表和数组用于存储有序的数据集合,例如学院球队中每名球员的 20 米冲刺时间。列表允许你通过索引访问单个数值,对其进行循环,并快速计算汇总统计。
sprint_times = [3.12, 3.08, 3.21, 2.98, 3.15]
To calculate the mean time, you can sum all values and divide by the number of values. The mean is often used as a baseline for comparing individual performance against the group.
要计算平均时间,可以将所有数值相加,再除以数值的个数。平均值通常用作比较个人表现与集体水平的基准。
mean = (x₁ + x₂ + x₃ + x₄ + x₅) ÷ 5
Beyond the mean, arrays make it easy to find the fastest player, sort athletes by score, or select only those who are above a cut-off time. These operations are essential when preparing team selections or monitoring progress over a season.
除了平均值,数组还可以轻松找出最快的球员、按成绩排序运动员,或只选择超过截止时间的选手。这些操作在准备球队选拔或监测整个赛季进展时至关重要。
6. File Input and Output | 文件输入与输出
Real sports datasets are rarely typed by hand; they are stored in files such as CSV or JSON. A practical programmer must be able to read data from a file, process it, and write results back to a new file. This is called file input and output, or file I/O.
真实的体育数据集很少手动输入,它们通常存储在 CSV 或 JSON 等文件中。一个实用的程序员必须能够从文件读取数据、处理数据,并将结果写回新文件。这称为文件输入与输出(file I/O)。
For example, a CSV file might contain columns for player name, match minutes, distance covered, and number of sprints. The program opens the file, reads each row, and converts the columns into appropriate data types before analysis.
例如,一个 CSV 文件可能包含球员姓名、比赛时间、跑动距离和冲刺次数等列。程序打开文件,逐行读取,并将各列转换为合适的数据类型后再进行分析。
read match_data.csv
for each row:
player_name = row[0]
distance_km = float(row[2])
process player data
After processing, the results can be written to an output file, such as a summary report or a new CSV ready for graphing. Good file I/O habits include closing files properly and checking that the expected columns exist.
处理之后,结果可以写入输出文件,比如汇总报告或准备好绘图的新 CSV。良好的文件 I/O 习惯包括正确关闭文件,并检查是否存在预期的列。
7. Data Validation and Error Handling | 数据验证与错误处理
Not all data collected in sport is clean. A heart-rate monitor may fail, a time may be entered as text, or a value may be missing. Data validation checks for unreasonable or incorrect input before processing, while error handling prevents the program from crashing when something goes wrong.
并非所有体育数据都是干净的。心率监测器可能失灵,时间可能被输入为文本,或者某些值可能缺失。数据验证在处理前检查不合理或不正确的输入,而错误处理则防止程序在出错时崩溃。
For example, a sprint time should always be positive and within a realistic range. The following rule can be applied: if the time is less than 0 or greater than 30 seconds, mark the record for review.
例如,冲刺时间应始终为正数,并且在合理范围内。可以应用以下规则:如果时间小于 0 或大于 30 秒,则将该记录标记为待审核。
try:
time_s = float(input_value)
except ValueError:
print('Invalid time format')
This try-except structure is an example of defensive programming. It ensures that one bad record does not stop the entire analysis. The same technique can be used to catch missing files, network errors, or incorrect column names.
这种 try-except 结构是防御性编程的一个示例。它确保一条坏记录不会停止整个分析。同样的技术也适用于捕获缺失文件、网络错误或错误的列名。
8. Data Visualisation for Performance | 表现数据可视化
Raw numbers are difficult to interpret, so sports scientists often convert them into charts. A line graph can show how a player's resting heart rate changes over a training month, while a bar chart can compare the sprint times of different athletes.
原始数字难以解读,因此运动科学家通常将其转换为图表。折线图可以显示球员静息心率在一个训练月内的变化,而条形图可以比较不同运动员的冲刺时间。
Using a programming library such as matplotlib, you can create visualisations with only a few lines of code. The data must first be organised into lists or arrays, then passed to the plotting function with clear axis labels.
使用 matplotlib 等编程库,只需几行代码即可创建可视化。数据必须先组织成列表或数组,然后传给绘图函数,并添加清晰的轴标签。
plot(training_days, resting_heart_rate)
title('Resting Heart Rate Trend')
xlabel('Day')
ylabel('Beats per minute')
Visualisation is not just about making data look attractive. It helps coaches spot overtraining, identify outliers, and communicate findings to athletes who may not be comfortable reading raw data tables.
可视化不仅仅是为了让数据看起来有吸引力。它可以帮助教练发现过度训练、识别异常值,并向不习惯阅读原始数据表的运动员传达研究结果。
9. Testing, Debugging and Documentation | 测试、调试与文档
Even experienced programmers make mistakes. Practical programming therefore includes systematic testing, debugging, and documentation. Unit tests check that individual functions return the expected outputs for known inputs, making errors easier to locate.
即使是经验丰富的程序员也会犯错。因此实用编程包括系统性的测试、调试和文档编写。单元测试检查单个函数在已知输入下是否返回预期输出,使错误更容易定位。
When a bug occurs, a simple debugging technique is to print intermediate values. If a speed calculation returns a negative number, printing distance and time before the division often reveals that the time was entered as a negative value.
当出现错误时,简单的调试技巧是打印中间值。如果速度计算返回负数,在除法之前打印距离和时间通常会发现时间被输入为负值。
print(distance_m, time_s, speed_ms)
Documentation means writing comments in the code and keeping an updated README file. It helps other analysts understand the project and allows you to return to the code months later without confusion.
文档意味着在代码中编写注释,并维护一个更新的 README 文件。它有助于其他分析师理解项目,也使你在几个月后重新阅读代码时不会感到困惑。
10. Mini Project: Building a Player Monitoring Tool | 小项目:构建球员监测工具
To bring all the techniques together, consider building a simple player monitoring tool. The tool reads a CSV file containing daily records of player name, training load, and resting heart rate. It then calculates the average heart rate for each player and writes a short summary.
为了将所有技术结合起来,可以考虑构建一个简单的球员监测工具。该工具读取包含球员姓名、训练负荷和静息心率每日记录的 CSV 文件,然后计算每名球员的平均心率,并写出简要摘要。
The project can be divided into clear steps: load the file, validate the data, group records by player, compute averages, and output the results. Each step can be written as a separate function and tested individually before linking them together.
该项目可以分成明确的步骤:加载文件、验证数据、按球员分组记录、计算平均值并输出结果。每一步都可以写成一个单独的函数,在连接之前分别测试。
- Step 1: Read CSV file and skip empty rows.
- Step 2: Convert heart rate to a number and reject invalid values.
- Step 3: Use a dictionary to group heart rates by player.
- Step 4: Calculate the mean for each player.
- Step 5: Write a summary file or display a bar chart.
- 步骤 1:读取 CSV 文件并跳过空行。
- 步骤 2:将心率转换为数字并拒绝无效值。
- 步骤 3:使用字典按球员对心率进行分组。
- 步骤 4:计算每名球员的平均值。
- 步骤 5:写出摘要文件或显示条形图。
This mini project mirrors the workflow used by real sports science departments. It demonstrates that practical programming is not about memorising syntax, but about solving problems with clear structure, careful validation, and reproducible steps.
这个小项目模拟了真实运动科学部门使用的工作流程。它表明实用编程不是记忆语法,而是用清晰的结构、仔细的验证和可重复的步骤来解决问题。
Published by TutorHao | Physical Education Revision Series | aleveler.com
更多咨询请联系16621398022(同微信)

或截图后用「扫一扫 → 相册」选择本图