python - 如何将压缩列表项相互相乘?

标签 python python-3.x lambda list-comprehension

我正在做一个练习,我创建了一个函数,该函数接收两个列表并返回单独列表中相同索引处的项目的乘积。示例:

transform("1 5 3", "2 6 -1")
#should return
[2, 30, -3]

为了清楚起见,该程序采用索引 1、2 和 3 处的项目并将它们相乘,如下所示:

(1 * 2), (5 * 6), (3 * -1)

现在,我面临的问题是在程序中必须使用zip()函数,我还没有正确使用。

我已经制作了一个成功完成一般任务的程序,但我想不出一个使用压缩列表的解决方案。谁能帮我解决这个问题?我有一个想法,我可以使用我在 map() 函数中创建的压缩列表“q”,但我不知道如何使用。

这是我的程序:

def transform(s1, s2):
    i = 0

    s = s1.split(' ')
    d = s2.split(' ')

    while i < len(s):
        try:
            s[i] = int(s[i])
            d[i] = int(d[i])
            i += 1
        except ValueError:
            break

    print(s, d)

    q = list(zip(s, d))
    print(q)

    final = list(map(lambda x, y: x * y, s, d))

    return final

def main():
    print(transform("1 5 3", "2 6 -1"))

if __name__ == "__main__":
    main()

提前感谢任何提供帮助的人!

最佳答案

这应该做你想做的:

def transform(a, b):
     return [int(i) * int(j) for i, j in zip(a.split(), b.split())]



a = "1 5 3"
b = "2 6 -1"
print(transform(a, b))  # [2, 30, -3]

使用splitzip应该是直截了当的。然后是list comprehension创建列表。

关于python - 如何将压缩列表项相互相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64487060/

相关文章:

python - 构建包含可变大小小部件的 QT Designer 布局

python - FastAPI 保存上下文将在端点中可用

python - "Cast"到 Python 3.4 中的 int

python - 工作线程内的 Queue.put 失败

python - 默认的 Django 管理表单和 FormWizard

python - 用于获取链接的 Beautifulsoup 和 Soupstrainer 不适用于 hasattr,始终返回 true

c# - linq-to-sql 查询结果到 c# 字典 - 如何

C++11 lambdas 和方括号

java - 在java流中映射和应用

python - 从列表列表中获取独特的项目?