You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用$hole变量命名变量优化PowerShell高尔夫计分统计脚本

高尔夫球成绩统计脚本修正方案

原代码问题分析

  • 单个命名的标准杆变量($par1到$par18)无法通过$par[$hole]动态访问,需改为数组形式
  • 计数逻辑错误:$albatrosCount[$hole] = $albatrosCount[$hole] + $albatrosCount[$hole]会将当前值翻倍,而非累加有效计数
  • 大量重复的while循环,代码冗余度极高
  • 未正确初始化计数数组,且使用多个独立数组管理计数,维护性差

修正后代码

# 定义18洞标准杆,数组索引1-18对应洞号(索引0空置)
$par = @(0,4,5,4,3,4,4,3,5,4,4,4,5,4,3,4,3,4,5)

# 定义成绩类型与标准杆的差值规则,用哈希表统一管理
$scoreTypes = @{
    "信天翁" = -3
    "老鹰球" = -2
    "小鸟球" = -1
    "标准杆" = 0
    "柏忌" = 1
    "双柏忌" = 2
    "更差成绩" = $null # 用null标记特殊判断逻辑
}

# 初始化计数结构:每个成绩类型对应一个数组,存储18洞的计数
$scoreCounts = @{}
foreach ($type in $scoreTypes.Keys) {
    $scoreCounts[$type] = @(0) * 19 # 索引0不用,1-18对应洞号
}

# 遍历球员成绩统计
foreach ($entry in $eclecticResults) {
    foreach ($hole in 1..18) {
        $holePar = $par[$hole]
        $playerScore = $entry.$hole
        $scoreDiff = $playerScore - $holePar

        # 匹配成绩类型并更新计数
        foreach ($type in $scoreTypes.Keys) {
            $targetDiff = $scoreTypes[$type]
            if ($targetDiff -ne $null) {
                if ($scoreDiff -eq $targetDiff) {
                    $scoreCounts[$type][$hole]++
                }
            } else {
                # 处理"更差成绩"的特殊判断
                if ($scoreDiff -gt 2) {
                    $scoreCounts[$type][$hole]++
                }
            }
        }
    }
}

# 整理输出统计结果
$statsList = @()
foreach ($type in $scoreTypes.Keys) {
    $row = [PSCustomObject]@{
        "类型" = $type
        "1" = $scoreCounts[$type][1]
        "2" = $scoreCounts[$type][2]
        "3" = $scoreCounts[$type][3]
        "4" = $scoreCounts[$type][4]
        "5" = $scoreCounts[$type][5]
        "6" = $scoreCounts[$type][6]
        "7" = $scoreCounts[$type][7]
        "8" = $scoreCounts[$type][8]
        "9" = $scoreCounts[$type][9]
        "10" = $scoreCounts[$type][10]
        "11" = $scoreCounts[$type][11]
        "12" = $scoreCounts[$type][12]
        "13" = $scoreCounts[$type][13]
        "14" = $scoreCounts[$type][14]
        "15" = $scoreCounts[$type][15]
        "16" = $scoreCounts[$type][16]
        "17" = $scoreCounts[$type][17]
        "18" = $scoreCounts[$type][18]
        "总计" = ($scoreCounts[$type][1..18] | Measure-Object -Sum).Sum
    }
    $statsList += $row
}

# 输出结果
$statsList | Format-Table -AutoSize

关键优化点

  • 将标准杆改为数组$par,通过$par[$hole]直接访问对应洞的标准杆
  • 用哈希表$scoreTypes统一管理成绩类型与差值的对应关系,避免重复逻辑
  • 单个嵌套循环完成所有洞和成绩类型的统计,消除冗余代码
  • 用哈希表$scoreCounts集中管理所有成绩类型的计数数组,提升可维护性
  • 修复计数逻辑错误,正确累加每个洞的对应成绩数量

内容的提问来源于stack exchange,提问作者Michel Balencourt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 03:42:37