python - 在两个列表中循环

标签 python

我有这些列表:

list1 = [3, 5, 2, 1, 9]
list2 = [6, 9, 1, 2, 4]
list3 = []
list4 = []

我想传递这些公式:

x = a/b
y = 1/b

其中 a 是 list1 中的每个值,b 是 list2 中的每个值,并将计算结果附加到两个空列表 - list3 和 list4。

这就是我所拥有的,但这是一场灾难哈哈:(

u = 0
while u<len(list1):
    for a in list1:
        for b in list2:
            x = a/b
            y = 1/b
            u+=1
            list3.append(x,)
            list4.append(y,)

谁能帮我解决这个问题?

最佳答案

这是一个单行本:

>>> list3,list4 = zip(*[(a/b,1/b) for a,b in zip(list1,list2)])
>>> list3
(0, 0, 2, 0, 2)
>>> list4
(0, 0, 1, 0, 0)

输出是元组。但它们可以很容易地转换为 list

哦。通过使用 generator expression 而不是 list comprehension 可以使内存效率更高:

>>> zip(*((a/b,1/b) for a,b in zip(list1,list2)))

关于python - 在两个列表中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166177/

相关文章:

python - 一些基本的 tkinter 问题

python - 从列表 Python 3.3.4 中获取具有最高整数的变量名称

python - Plotly:向条形图添加线条

python - 在多维数据中将字符串更改为数字

python - 如何使用 numpy 加速 Python 代码?

python - Django 重定向到模板传递模型

python - cv2.dnn' 使用 python 3.6 和 opencv3.4.1 没有属性 'readNet'

python - 使用 python 从 csv 文件读取并放入具有不同字段类型的 Mysql

python - 如何在 Pycharm 中运行 Scrapy 单元测试

python - 使用 asyncio.Queue 将数据从子流程安全地传递到异步任务