python - 如何在添加 "coefficient"的同时合并列表中的重复元素?

标签 python list

我正在编写一个函数“simplify”来简化多项式,以便 simplify("2xy-yx") 可以返回 "xy", simplify( "-a+5ab+3a-c-2a")可以返回"-c+5ab"等等。

我正处于将多项式分解为多个单项式作为列表元素的阶段,并将单项式的系数和字母(变量)部分分开。

例如

input = '3xy+y-2x+2xy'

我的过程给了我:

Var = ['xy', 'y', 'x', 'xy']
Coe = ['+3', '+1', '-2', '+2']

我想要做的是合并相同的单项式,并同时将另一个列表中相应的系数相加。

我的代码是:

Play1 = Letter[:]
Play2 = Coe[:]
for i in range(len(Play1) - 1):
    for j in range(i+1, len(Play1)):
        if Play1[i] == Play1[j]:
            Letter.pop(j)
            Coe[i] = str(int(Play2[i]) + int(Play2[j]))
            Coe.pop(j)

但这似乎只适用于每个重复元素出现不超过两次的列表。例如,输入“-a+5ab+3a-c-2a”给我:

IndexError: pop index out of range

我想过使用set,但这会改变顺序。

最好的方法是什么?谢谢。

最佳答案

使用 zip() 组合您的列表以便于处理,并创建一个新列表:

newVar = []
newCoe = []

for va, co in zip(Var, Coe):

    # try/except (EAFP) is very Pythonic
    try:
        # See if this var is seen
        ind = newVar.index(va)

        # Yeah, seen, let's add the coefficient
        newCoe[ind] = str(int(newCoe[ind]) + int(co))

    except ValueError:
        # No it's not seen, add both to the new lists
        newVar.append(va)
        newCoe.append(co)

由于所有项目都按其原始顺序进行处理,并且使用列表追加而不是哈希表(如 setdict),因此顺序被保留。

关于python - 如何在添加 "coefficient"的同时合并列表中的重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543048/

相关文章:

python - 回顾数据框中的上一行并选择特定记录

python - 使用 4 邻域进行骨架化

python - 使用 WSDiscovery 从服务列表中获取特定字符串

list - 将 0-s 添加到列表中,直到它的长度在 Haskell 中为 8

c# - 如何创建列表<编译时未知类型>并通过 System.Reflection.PropertyInfo 复制项目

Python:pexpect 不执行 `backtick` 命令

python - Pandas 仅从右侧替换

python - 我怎样才能改进这个 number2words 脚本

python - 检查给定 float 落在列表中的哪个 float 之间

MySQL逗号分隔字段查询