基于数字部分: '5a+6b' + '2a+3b+9c' = '7a+9b+9c' 的Python字符串处理

标签 python

我需要添加两个简单的多项式(表示为字符串)。以下示例将阐明我的要求。

input1 = '5a+6b'
input2 = '2a+3b+9c'

所需金额应如下所示:

 '7a+9b+9c'

目前我已经创建了一个函数(20 行)来为我执行此任务,但我认为这可以改进。

编辑:添加我的代码

def add_domain_strings():
    input_list = ['5a+6b', '2a+3b+9c']
    vars_dict = {}
    for input in input_list:
        temp_list = input.split('+')
        for i in temp_list:
            split_index = None
            for j in i:
                if not j.isdigit():
                    split_index = i.index(j)
                    break
            if i[split_index:] in vars_dict:
                vars_dict[i[split_index:]] += int(i[:split_index])
            else:
                vars_dict[i[split_index:]] = int(i[:split_index])
    sum_string = ''
    for k,v in vars_dict.iteritems():
        if sum_string:
            sum_string += '+%s%s' % (v,k)
        else:
            sum_string += '%s%s' % (v,k)
    return sum_string

最佳答案

sympy 确实接近你想要的

>>> import sympy
>>> a,b,c = sympy.symbols('abc')
>>> 5*a+6*b + 2*a+9*b+9*c
7*a + 9*c + 15*b

关于基于数字部分: '5a+6b' + '2a+3b+9c' = '7a+9b+9c' 的Python字符串处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6609982/

相关文章:

从 cron 或 subshel​​l 使用绝对路径调用时,Python 不会退出

python - 通过整数索引选择一行 Pandas 系列/数据框

python - 使用 multiprocessing.Managers 构建一个简单的远程调度程序

python 函数无法正常工作,它不会返回用户应该获得的值

python - 使用 python h5py 读取 .mat 文件中的所有变量

python - 具有灵活聚合周期的按 pandas 分组的数据帧的平均值

python - Pandas DataFrame 循环遍历所有列

python - 捕获数字列的新列中是否存在 NA

python - 编写一个名为 filter_out() 的函数,该函数将整数列表作为输入,并返回仅保留数字过滤的列表

python - 给定 (5,2) 张量,删除第二列中具有重复项的行