如何将列表中的每个数字乘以第二个列表中的数字,并将每个输出附加到新列表中?
示例:
mylist = [1, 2, 3, 4]
testnumbers = [1, 5, 10]
输出:
newlist1 = [1, 2, 3, 4,]
newlist2 = [5, 10, 15, 20]
newlist3 = [10, 20, 30, 40]
答案 0 :(得分:1)
我们从两个列表开始。
mylist = [1, 2, 3, 4]
testnumbers = [1, 5, 10]
现在,我们希望mylist
的每个元素都需要与testnumbers
中的元素相乘,因此我们需要一个嵌套的for循环
#Take an element from testnumbers
for test in testnumbers:
newlist = []
#Multiply it with each element of mylist, and append it to a list
for elem in mylist:
value = elem*test
newlist.append(value)
print(newlist)
#[1, 2, 3, 4]
#[5, 10, 15, 20]
#[10, 20, 30, 40]
要迈出第一步,我们可以将所有这些列表附加到更大的列表中
results = []
for test in testnumbers:
newlist = []
for elem in mylist:
value = elem*test
newlist.append(value)
results.append(newlist)
print(results)
#[[1, 2, 3, 4], [5, 10, 15, 20], [10, 20, 30, 40]]
答案 1 :(得分:0)
将第二个列表中的每个元素放在上方,再与第一个列表中的每个元素相乘,以创建一个新列表。
res = []
for x in testnumbers:
res.append([x * i for i in mylist])
print(res)
答案 2 :(得分:0)
[[ x * i for i in mylist] for x in testnumbers]
输出
[[1, 2, 3, 4], [5, 10, 15, 20], [10, 20, 30, 40]]