如何在Python中舍入到特定值

Fre*_*e R 10 python function rounding

我正在研究一种自动为角色扮演游戏创建角色表的算法.在游戏中,你有一些属性,你可以用它来增加它们.但是,在某个值处,需要2个点才能将实际属性的值增加1.您可以使用一定数量的点开始,默认情况下每个属性的值为1

我有一个随机分配点的程序,但是我不知道如何在必要时将这些值(在字典中)更改为舍入.

例如,如果我在"强度"中加入3分,那很好,我的"强度"值为3(包括基数1).但是,如果我输入4个点,我仍然应该只有4个值.它应该取5个点(加上基数1)以获得值5.然后需要另外2个点来获得值6,3点得到7值和3点得到值8.

我目前用来分配attibutes的代码如下所示:

attributes = {}
row1 = ['strength', 'intelligence', 'charisma']
row2 = ['stamina', 'willpower']
row3 = ['dexterity', 'wits', 'luck']

def assignRow(row, p): # p is the number of points you have to assign to each row
    rowValues = {}
    for i in range(0, len(row)-1):
        val = randint(0, p)
        rowValues[row[i]] = val + 1
        p -= val
    rowValues[row[-1]] = p + 1
    return attributes.update(rowValues)

assignRow(row1, 7)
assignRow(row2, 5)
assignRow(row3, 3)
Run Code Online (Sandbox Code Playgroud)

我想要的只是一个简单的函数,它将字典"attributes"作为参数,并将每个属性所具有的点数转换为它应该具有的正确值.

"strength": 4保持"strength": 4,但"wits": 6"往下走"wits": 5",然后"intelligence: 9下去"intelligence: 7".

我对使用字典有些新意,所以我通常会采用这种方法:

def convert(list):
    for i in range(len(list)):
        if list[i] <= 4:
            list[i] = list[i]
        if list[i] in (5, 6):
            list[i] -= 1
        if list[i] in (7, 8):
            list[i] -= 2
        if list[i] in (9, 10):
            list[i] = 6
        if list[i] in (11, 12, 13):
            list[i] = 7
        else:
            list[i] = 8
Run Code Online (Sandbox Code Playgroud)

不高效或漂亮,但仍然是一个解决方案.但是,你不能只是在字典中循环索引,所以我不完全确定如何去做这样的事情.

一般解释或功能将不胜感激.

Sla*_*lam 7

似乎二分算法非常适合您的需求 - 指向"投资"总是被排序和定义.创建带有参考点的数组,没有一堆ifs 你会很好:

>>> from bisect import bisect
>>> points_to_invest = [1, 2, 3, 4, 6, 8, 10, 13]
>>> bisect(points_to_invest, 1)
1
>>> bisect(points_to_invest, 4)
4
>>> bisect(points_to_invest, 5)
4
>>> bisect(points_to_invest, 6)
5
Run Code Online (Sandbox Code Playgroud)

这种方法可以为您的未来提供更轻松的可维护性