在Python中创建具有多重性的项列表

2024-06-02 06:38:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对创建列表有一个问题。在

我有一个函数,返回多项式的根(见下文)。我得到的是一个根的列表(R.keys()),以及每个根在解决方案中出现的次数(R.values())。在

当我得到R.items()时,我得到了一组根对及其重数:[(-2, 2), (-1, 1), (-3, 3)],如下例所示。在

但是我想要的是获得一个列表,每个根重复出现的次数,即[-2, -2, -1, -3, -3, -3]。在

我想这并不难,但我正忙于寻找解决办法。在

pol=Lambda((y), y**6 + 14*y**5 + 80*y**4 + 238*y**3 + 387*y**2 + 324*y + 108)
poli=Poly(pol(y))
R=roots(poli)
R.keys()
R.values()
R.items()

def list_of_roots(poli):
    return(R.items())
list_of_roots(poli)

Tags: of函数列表itemskeys解决方案次数list
3条回答
roots = [(-2, 2), (-1, 1), (-3, 3)]
[ r for (root, mult) in roots for r in [root] * mult]

[-2, -2, -1, -3, -3, -3]
def get_list_of_roots(poli):
    # initialize an empty list 
    list_of_roots = []
    # process your poli object to get roots
    R = roots(poli)
    # we obtain the key value pairs using R.items()
    for root, multiplicity in R.items():
        # extend the list_of_roots with each root by multiplicity amount
        list_of_roots += [root] * multiplicity
    return list_of_roots

编辑:在函数中处理poli,因为您似乎希望将poli传递给它。在

编辑:增加代码解释。在

如果您可以获得Array<Tuple>形式的项目列表,那么您可以创建一个list,如下所示:

items = [(-2, 2), (-1, 1), (-3, 3)]
listOfRoots = []
for x in items:
    for y in range(x[1]):
        listOfRoots.append(x[0])
print(listOfRoots)

相关问题 更多 >