Skip to main content
 首页 » 编程设计

python之在 python 中添加字符串(作为 base 12 数字的表示)和整数/其他字符串

2024年12月31日23oomusou

我需要创建一个计算器,它可以将以 12 为基数的数字相加,并且在不同的数字上有不同的限制。

12 位序列:[0,1,2,3,4,5,6,7,8,9,"A","B"]

限制必须是:

  • 第一位数字:限制“B”
  • 第二位:限制4

这意味着你会这样数:[1,2,3,4,5,6,7,8,9,A,B,10,11,...48,49,4A,4B]

但我不知道我该怎么做才能对 2 个数字求和

我在 python 中有以下代码:

list1=[0,1,2,3,4,5,6,7,8,9,"A","B"] 
list2=[0,1,2,3,4] 
list3=[0,1,2,3,4,5,6,7,8,9,"A","B"] 
list4=[0,1,2,3,4] 
 
 
def calculadora (entrada1, operacion, entrada2): 
    #parte de valor 1: 
    digito1_1=str(list2[int(entrada1//12)]) 
    digito1_2=str(list1[int(entrada1%12)]) 
    valor1=float(digito1_1+digito1_2) 
    #parte de valor 2 
    digito2_1=str(list2[int(entrada2//12)]) 
    digito2_2=str(list1[int(entrada2%12)]) 
    valor2=float(digito2_1+digito2_2) 
    if operacion==str("suma") or "+": 
        return float(valor1+valor2) 
entrada1 = float(input("inserte primer valor")) 
operacion=str(input("inserte operación")) 
entrada2 = float(input("inserte segundo valor")) 
print (calculadora(entrada1,operacion,entrada2)) 

它适用于数字,但我想对 3B 这样的数字求和,它给了我一个 ValueError,因为它被编码为字符串。

有人可以帮助我或告诉我如何计算这些数字的总和吗?

请您参考如下方法:

将 base-12 编码的字符串转换为 int 的最简单方法是通过 int(string, 12)。反过来就没那么容易了,因为 Python 似乎没有内置的方法来做到这一点。您可以对二进制、八进制和十六进制使用格式说明符,但不能使用任意基数。

您可以使用 divmod() 得到一个反转的数字列表,它用余数除法。

def to_digits(x, base): 
     while x > 0: 
         x, rem = divmod(x, base) 
         yield rem 

但是为了往返,我们需要一个字符串。将 int 转换为一个字符(使用一个字符串作为查找表),并将它们连接成一个字符串,然后使用负步进切片将其反转。

def to_base_12(num): 
    return ''.join('0123456789AB'[d] for d in to_digits(num, 12))[::-1] 

使用更长的查找表,您可以将其推广到更高的基数。

字符串已经是序列了,但是如果你想把它转换回一个列表,你可以只调用 list() 就可以了。相反的是您刚刚看到的 ''.join() 方法。

现在您可以将 base-12 表示形式转换为 Python int 对象并返回,您只需使用 + 添加它们即可。