l2=[[13,11,9],[7,5,3],[1]]
我想将列表l2
中的每个子列表乘以一个常数,即13 * 1,11 * 1,9 * 1和7 * 2,5 * 2,3 * 2和1 * 3,以及最终结果将是13,11,9和14,10,6和3。
答案 0 :(得分:1)
使用enumerate
例如:
l2=[[13,11,9],[7,5,3],[1]]
print([[j*i for j in v] for i, v in enumerate(l2, 1)])
输出:
[[13, 11, 9], [14, 10, 6], [3]]
答案 1 :(得分:0)
您可以在此处利用enumerate
:
l2 = [[13,11,9],[7,5,3],[1]]
l3 = [[x * (idx + 1) for x in sublist] for idx, sublist in enumerate(l2)]
print(l3)
这产生
[[13, 11, 9], [14, 10, 6], [3]]
答案 2 :(得分:0)
尝试一下:
l2=[[13,11,9],[7,5,3],[1]]
counter = 1
for i in range(len(l2)):
for j in range(len(l2[i])):
l2[i][j] *= counter
counter += 1
print(l2)
答案 3 :(得分:0)
是否总是第一个子列表是1,第二个是两个,依此类推?
for i in range(0, len(l2)):
i += 1
print(f'{l2[i-1]} times {i}')
print(list(map(lambda x: x*i, l2[i-1])))
答案 4 :(得分:0)
一个带有map
和enumerate
的衬纸
[map((idx).__mul__, sublist) for idx,sublist in enumerate(l2,1)] #[[13, 11, 9], [14, 10, 6], [3]]
使用numpy.multiply
import numpy as np
[np.multiply(sublist,[idx]).tolist() for idx,sublist in enumerate(l2,1)]
答案 5 :(得分:0)
new_list = []
multiplier = 1
# passing over sublists( e.g. [13,11,9] = li) in l2
for li in l2:
# multiply all elements in sublist(li) with multiplier(in first step multiplier = 1)
# append the multiplied sublist to the new list
new_list.append([li[i]*multiplier for i in range(len(li))])
# multiplier increase by one (e.g. in second step we need to multiply elements from second sublist with multiplier = 2)
multiplier += 1
print (new_list)