我有一个赋值,只使用基本的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:“不能将这两个方法的序列与'list'类型的非int相乘。”是否有更有效的方法将两个“列表列表”中的每个元素相乘?
答案 0 :(得分:0)
尝试这种方法:
results = []
for i,j in zip(squares,logs)
x = i*j
results.append(x)
答案 1 :(得分:0)
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 ...]等],然后使用以下代码: -
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 ...]等],然后使用以下代码: -
log_mul_sqr = [[m*n for m in squares] for n in logs]
此外,这将消除您在#4
创建的squareslol
和logslol
创建的开销