拯救棒球投球局

2024-09-28 21:34:00 发布

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

我真的不知道从哪里开始

我有一个Django表单,在其中我将棒球统计数据保存到我的数据库中。我的问题在于投球局数

在棒球比赛中,局数是以三分之一来衡量的,但不是以.33、.66、.99来衡量,而是以.1、.2、.0来表示

例如,一个投手可以投5局,5.1局,5.2局,6局

如何以这种方式存储和操作数据

谢谢你的帮助


Tags: 数据django数据库表单方式统计数据棒球投手
1条回答
网友
1楼 · 发布于 2024-09-28 21:34:00

简单的解决方案可能是创建两个实用函数,将传统的表示法转换为三分之一数,反之亦然

def innings_to_thirds(score):
    score = float(score) #  we can accept floats or strings: 5.2 or "5.2"
    # 5.2 means 5 times 3 thirds ...
    thirds = 3 * int(score)
    # plus 0.2 * 10 = 2 thirds
    thirds += (score - int(score)) * 10 
    return int(thirds)

def thirds_to_innings(thirds):
    # the parts of the inning notation are the quotient 
    # and remainder of the division by 3
    q, r = divmod(thirds, 3)
    inning = str(q)
    if r:
        inning += '.' + str(r)
    return inning    

一些测试:

innings = [0, "0.2", 1,  2.1, "2.2"]

for i in innings:
    print(f'{i} = {innings_to_thirds(i)} thirds')
    
thirds = [0, 2, 3, 7, 8]

for t in thirds:
    print(f'{t} thirds -> {thirds_to_innings(t)}')

输出:

0 = 0 thirds
0.2 = 2 thirds
1 = 3 thirds
2.1 = 7 thirds
2.2 = 8 thirds
0 thirds -> 0
2 thirds -> 0.2
3 thirds -> 1
7 thirds -> 2.1
8 thirds -> 2.2

相关问题 更多 >