gpt4 book ai didi

python - "How to unevenly iterate over two lists"

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:23 26 4
gpt4 key购买 nike

我无法找到针对这个非常具体的问题的解决方案。本质上,我有两个列表,每个列表有两个元素:[A, B] 和 [1,2]。我想创建一个嵌套循环,在第二个列表上迭代和扩展,并在每次迭代后添加第一个列表的每个元素。

我最终想看到的是这样的:

A B 
1 A
1 B
2 A
2 B
1 1 A
1 2 A
2 1 A
2 2 A
1 1 B
1 2 B
2 1 B
2 2 B
1 1 1 A
1 1 2 A
...

我的问题是,我尝试递归地将 A 和 B 分开,以便出现这种模式(也请注意不同的第一行):

A
1 A
2 A
1 1 A
1 2 A
2 1 A
2 2 A
1 1 1 A
1 1 2 A
...
B
1 B
2 B
1 1 B
1 2 B
2 1 B
2 2 B
1 1 1 B
1 1 2 B
...

如何将 A 和 B 放在一起?

这是代码:

def second_list(depth):
if depth < 1:
yield ''
else:
for elements in [' 1 ', ' 2 ']:
for other_elements in list (second_list(depth-1)):
yield elements + other_elements


for first_list in [' A ', ' B ']:
for i in range(0,4):
temp=second_list(i)
for temp_list in list(temp):
print temp_list + first_list

最佳答案

我会尝试以下风格的东西:

l1 = ['A', 'B']
l2 = ['1', '2']

def expand(l1, l2):
nl1 = []
for e in l1:
for f in l2:
nl1.append(f+e)
yield nl1[-1]
yield from expand(nl1,l2)

for x in expand(l1, l2):
print (x)
if len(x) > 5:
break

注意:输出的第一行似乎不是同一规则的产物,因此它不是在这里生成的,如果需要,您可以手动添加它。

注2:不构建新生成元素的列表会更优雅,但这样你就必须计算它们两次。

关于python - "How to unevenly iterate over two lists",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53960480/

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