如何:将一个列表与另一个列表中的数字相乘,并在新列表中输出所有数据

2024-09-27 21:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将列表中的每个数字与第二个列表中的数字相乘,并将每个数字的输出附加到新列表中?你知道吗

示例:

mylist = [1, 2, 3, 4]
testnumbers = [1, 5, 10]

输出:

newlist1 = [1, 2, 3, 4,]
newlist2 = [5, 10, 15, 20]
newlist3 = [10, 20, 30, 40]

Tags: 示例列表数字mylisttestnumbersnewlist1newlist2newlist3
3条回答
[[ x * i for i in mylist] for x in testnumbers]

输出


[[1, 2, 3, 4], [5, 10, 15, 20], [10, 20, 30, 40]]

我们从两个列表开始。你知道吗

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]]

循环第二个列表中的每个元素,与第一个列表中的每个元素相乘以创建一个新列表。你知道吗

res = []
for x in testnumbers:
    res.append([x * i for i in mylist])
print(res)

相关问题 更多 >

    热门问题