python - 如何舍入到 Python 中的特定值

标签 python function rounding

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

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

例如,如果我在“强度”中加了 3 分,那没关系,我得到的“强度”值为 3(包括基数 1)。但是,如果我输入 4 点,我仍然应该只有 4 的值。它应该需要 5 点(加上基数 1)才能得到 5 的值。然后再需要 2 点才能得到值6、3分得7分,3分得8分。

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

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)

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

"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

效率不高或不漂亮,但仍然是一个解决方案。但是,您不能只循环遍历字典中的索引,所以我不完全确定如何处理这样的事情。

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

最佳答案

似乎bisection算法非常适合您的需求——指向“投资”的点总是被分类和定义。创建带有引用点的数组,没有一堆 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

这种方法会让你在未来更容易维护

关于python - 如何舍入到 Python 中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331500/

相关文章:

C++:如何将 double 舍入为 int?

javascript - 了解闭包中的变量错误?

java - 客户余额比例作为其货币的指数

python - 无法在 Mac OS X Yosemite 上安装 openfst python 库

python - 使用 BeautifulSoup 输出 <br> 而不是 <br/>

javascript - 实际计算数与我用javascript函数计算的数之间的区别

java - 列出函数中接收到的类似对象

Ruby:根据任意数字列表将数字舍入到最接近的数字

python - 将对象的子集提取为字符串

python - 如何让 python 在 Visual Studio Code MacOS 中运行