首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我是否可以迭代地从这些单独的列表中切分所需的位置,并将它们放入另一个列表“系数”中,如下所示?

我是否可以迭代地从这些单独的列表中切分所需的位置,并将它们放入另一个列表“系数”中,如下所示?
EN

Stack Overflow用户
提问于 2021-03-09 13:53:27
回答 2查看 23关注 0票数 1

我想要做的是迭代每个p列表的位置,并将其放入coefficients中:暂停(在某种意义上),并使用np.roots()对这组系数进行计算。之后,迭代到每个p的下一个位置,并为下一次迭代生成:coefficients = [1, 3, 6, 9],然后继续进行更多的迭代。

代码语言:javascript
复制
p1 = [2, 3, 4]
p2 = [5, 6, 7]
p3 = [8, 9, 10]

coefficients = [1, p1[], p2[], p3[]]  # coefficients = [1, p1[0], p2[0], p3[0]] -> next comment
                                      # coefficients = [1,  2   ,     5,     8]
    
roots = np.roots(coefficients)

我想要的:

代码语言:javascript
复制
p1 = [2, 3, 4]
p2 = [5, 6, 7]
p3 = [8, 9, 10]


#After parsing through the data for the 1st iteration:
coefficients = [1,2,5,8]

#Calculate it with np.roots()
roots = np.roots(coefficients)

然后是下一次迭代:

代码语言:javascript
复制
#After parsing through the data for the 2nd iteration:
coefficients = [1,3,6,9] # coefficients = [1, p1[1], p2[1], p3[1]] -> next comment
                         # coefficients = [1,  3   ,     6,     9]

#Calculate it with np.roots()
roots = np.roots(coefficients)
EN

回答 2

Stack Overflow用户

发布于 2021-03-09 14:32:36

因此,我将您的问题转换为矩阵,并将返回的结果显示为矩阵。您可以使用此方法并将其扩展到所需的任意行数和列数。我使用的是矩阵运算。coefs是包含您想要的系数列表的矩阵,roots包含这些系数的根。

代码语言:javascript
复制
import numpy as np
# Let n be number of rows and m be number of columns

n = 3 # or number of lists
m = 3

# Save the data as a matrix
p = [[2, 3, 4],
     [5, 6, 7],
     [8, 9, 10]]

coefs = []
roots = []

for i in range(m):
    coef = [1,]
    for j in range(n):
        coef.append(p[j][i])
    
    # Add to the coefficients matrix and roots matrix
    coefs.append(coef)
    roots.append(np.roots(coef))

# Display results
print("Coefficient list 1", coefs[0])
print("Coefficient list 2", coefs[1])
print("Coefficient list 3", coefs[2])

print("Roots list 1", roots[0])
print("Roots list 2", roots[1])
print("Roots list 3", roots[2])

这就是输出的样子。

票数 1
EN

Stack Overflow用户

发布于 2021-03-09 14:44:15

你可以像这样连接你的数据:

代码语言:javascript
复制
coefficients = np.array([[1, 1, 1], p1, p2, p3]).T

不幸的是,np.roots只接受一个多项式,所以您必须将它们插入到一个循环中。

代码语言:javascript
复制
roots = [np.roots(p) for p in coefficients]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66541526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档