【问题标题】:Multiplying each element in two list of lists in python将python中两个列表列表中的每个元素相乘
【发布时间】:2016-08-26 01:21:12
【问题描述】:

我有一个任务是只使用基本的 python 函数(没有 numpy)生成以下列表。这是我所有的代码:

#1.Create a list which contains i^2 with i = 1 through 5
squares = [pow(i,2) for i in range(1,6)]
#print squares

#2. Create a list which contains log[j] with j = 1 through 5
logs = map(math.log10,range(1,6))
#print logs

#3. Create a list which contains [i_1*j_1, i_2*j_2, i_3,j_3...]
def mult(x,y): return x*y
lmultl = map(mult,squares,logs)
#print lmultl

#4 Create a list which contains [[i_1*j_1, i_1*j_2, i_1*j_3...][i_2*j_1, i_2*j_2, i_2*j_3...]etc]
logslol = [[logs]*5] #Returns a list of lists with 5 copies of list "logs"
def lrep(x): return [x,x,x,x,x] #Returns a list w/ 5 copies of each integer 
squareslol= map(lrep,squares) #Returns list of lists "for squares"

print map(mult,logslol,squareslol) #Attempt 1 to create goal list
print [logslol*item for item in squareslol] #Attempt 2 to create goal list 

我的问题是针对列表 #4 中的最终打印语句:我得到一个 TypeError:"can't multiply sequence by non-int of type 'list'" 对于这两种方法。有没有更有效的方法来将两个“列表列表”中的每个元素相乘?

【问题讨论】:

    标签: python math


    【解决方案1】:
    import math
    squares = [pow(i,2) for i in range(1,6)]
    logs = map(math.log10,range(1,6))
    
    mult = lambda x,y: x*y 
    lmultl = map(mult,squares,logs)
    

    我假设squares 中的元素是 i_1、i_2、i_3... logs 中的元素是 j_1, j_2, j_3...

    并且您想创建一个列表,将squares 的每个元素与logs 的每个元素相乘,其中包含 [[i_1*j_1, i_1*j_2, i_1*j_3...] [i_2*j_1, i_2* j_2, i_2*j_3...] etc],然后使用下面的代码:-

    sqr_mul_log = [[m*n for m in logs ] for n in squares]
    

    对于反向序列,即将logs 的每个元素与squares 的每个元素相乘,其中包含 [[j_1*i_1, j_1*i_2, j_1*i_3...] [j_2*i_1, j_2*i_2, j_2*i_3...] etc],然后使用下面的代码:-

    log_mul_sqr = [[m*n for m in squares] for n in logs]
    

    此外,这将消除您在 #4 处创建 squareslollogslol 的开销

    【讨论】:

    • 谢谢。我怀疑squareslollogslol 是不必要的。显示相反的顺序对于理解如何解释命令特别有帮助。
    • 一开始我很难理解你在第 4 步愿意做什么。我刚刚看到了 [i_1*j_1, i_1*j_2, ..], [i_2*j_1, i_2*j_2,...], etc...] 并编写了解决方案。
    【解决方案2】:

    试试这个方法:

    results = []
    for i,j in zip(squares,logs)
         x = i*j
         results.append(x)
    

    【讨论】:

    • 甚至results = list(map(lambda x: x[0]*x[1], zip(squares, logs)))
    • 以上两个建议都适用于将“squares”和“logs”列表中的元素相乘;但是,当将“squareslol”和“logslol”列表(即“列表列表”)中的元素相乘时,两个建议仍然返回与我的原始代码相同的 TypeError。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多