社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python——试图找出如何将两个列表的每个部分相乘

Jack • 3 年前 • 1320 次点击  

我试图计算一个列表中的每个元素乘以另一个列表中的每个元素的乘积。从每一个列表中,每个列表都是相乘的。

例如,在 list1 我有4,在清单2中需要乘以3。接下来是4英寸 清单1 需要乘以1英寸 list2 .模式将继续,直到我收到输出: [12,4,36,8,6,2,18,4,21,7,63,14] .我还没能做到这一点--以下是我目前掌握的代码:

def multiply_lists(list1,list2):
    for i in range(0,len(list1)):
        products.append(list1[i]*list2[i])
    return products

list1 = [4,2,7]
list2 = [3,1,9,2]
products = []
print ('list1 = ',list1,';','list2 = ', list2) 
prod_list = multiply_lists(list1,list2)
print ('prod_list = ',prod_list)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131032
 
1320 次点击  
文章 [ 4 ]  |  最新文章 3 年前
Ponprabhakar S
Reply   •   1 楼
Ponprabhakar S    3 年前

应该使用嵌套循环将两个或多个列表的元素相乘。

正确答案:

def multiply_lists(list1,list2):
    for i in list1:
        for j in list2:
            products.append(i*j)
    return products

list1 = [4,2,7]
list2 = [3,1,9,2]
products = []
print ('list1 = ',list1,';','list2 = ', list2) 
prod_list = multiply_lists(list1,list2)
print ('prod_list = ',prod_list)
flakes
Reply   •   2 楼
flakes    3 年前

你很接近。您真正想要的是两个for循环,这样您就可以将一个列表中的每个值与第二个列表中的所有值进行比较。例如

def multiply_lists(list1, list2):
    for i in range(len(list1)):
        for j in range(len(list2)):
            products.append(list1[i] * list2[j])
    return products

你也不需要 range col,您可以直接迭代每个列表的项:

def multiply_lists(list1, list2):
    for i in list1:
        for j in list2:
            products.append(i * j)
    return products

你也可以这样理解:

def multiply_lists(list1, list2):
    return [i * j for i in list1 for j in list2]
BrokenBenchmark
Reply   •   3 楼
BrokenBenchmark    3 年前

这里有两种简洁的方法。

第一次使用 itertools.product() 还有一份清单:

from itertools import product

[x * y for x, y in product(list1, list2)]

但是,这个问题非常适合于 itertools.starmap() ,这是第二种方法的动力。如果您不熟悉该函数,它会包含两个参数:

  • 接受两个参数的函数。在这种情况下,我们使用 operator.mul ,一种我们可以传递到函数中的乘法运算符。请注意,函数可以传递到Python中的其他函数中,因为函数是 first class .
  • 一个二号的小房间。在这种情况下,这是我们从 itertools。产品() .

对于iterable中的每个元素,它将元素解包,并将每个元素作为参数传递到第一个参数指定的函数中。这给了我们:

from itertools import product, starmap
import operator

list(starmap(operator.mul, product(list1, list2)))

这两种输出:

[12, 4, 36, 8, 6, 2, 18, 4, 21, 7, 63, 14]

如果您想将此方法扩展到两个以上的iTerable,可以这样做(如 flakes ):

from math import prod
list(map(prod, product(list1, list2, <specify more iterables>)))

其他答案建议使用多个选项 for 理解中的循环。注意 some consider this approach to be poor style ; 使用 itertools。产品() 完全避免这个问题。

如果你有任何问题,请随意评论——我非常乐意澄清任何困惑。我意识到这些解决方案可能不是最适合初学者的。至少,我希望这些方法对未来的读者有用。

Manjunath K Mayya
Reply   •   4 楼
Manjunath K Mayya    3 年前

像这样使用列表理解

print([i * j for i in list1 for j in list2])

输出:

[12, 4, 36, 8, 6, 2, 18, 4, 21, 7, 63, 14]