gpt4 book ai didi

python - 如何在不使用嵌套 for 循环的情况下迭代两个列表?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:32:36 24 4
gpt4 key购买 nike

如果 a 和 b 是两个列表,那么我们如何在不使用 python 中的嵌套 for 循环的情况下得到 c?

a=[1,2,3] 
b=[4,5,6]
c=[(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]

假设我必须找到由这些对形成的斐波那契数列的所有第 n 项的总和作为前两个数字,其中 n 是任何正数。在这种情况下,n=3 的答案是 63。

>     1 4 5 nth term in 5  1 5 6 nth term in 6  . . . 3 6 9 nth term in 9 
> > Sum of all nth term in 63.

最佳答案

只需使用 itertools 包中的 product 方法。

a=[1,2,3] 
b=[4,5,6]
c = list(itertools.product(a,b))
print(c)

输出

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

关于python - 如何在不使用嵌套 for 循环的情况下迭代两个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50202870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com