gpt4 book ai didi

python - 我的程序在比较两个列表时在 1 次迭代后停止

转载 作者:行者123 更新时间:2023-12-01 07:13:50 25 4
gpt4 key购买 nike

我有一个函数,它接受一个主列表,里面有 3 个列表,我想获取每个列表并将其与另一个包含 3 个元素的列表相关联。我希望主列表中的 3 个列表也发生这种情况。

我真的不明白为什么它只迭代一次。注意:如果我删除第 8 行,代码会执行相同的操作,但我将其留在那里,以便注意到我的意图,即希望对每个列表进行内部迭代:

for item1 in range(3):# and execute this loop 3 times

这是代码:

main_list =[["one","two","three"],["three","two","one"],["two","one","three"]]
comparison_list = ["element1","element2","element3"]

def correlator(list):
count = -1
for item in list:#I want to take each list
try:
for item1 in range(3):# and execute this loop 3 times
count += 1
print(f' {item[count]} is related to {comparison_list[count]}')

except IndexError:
pass

correlator(main_list)

结果是:

 one is related to element1
two is related to element2
three is related to element3

但我希望它是这样的:

  one is related to element1
two is related to element2
three is related to element3

three is related to element1
two is related to element2
oneis related to element3

two is related to element1
one is related to element2
three is related to element3

最佳答案

正如评论中所指出的,错误似乎是您没有重置计数器,因此出现 index out of range 错误。不知道为什么这里需要 try/ except 子句。为此,以下列表理解就足够了:

[f'{i} is related to {j}' for l in main_list for i,j in zip(l,comparison_list)]

['one is related to element1',
'two is related to element2',
'three is related to element3',
'three is related to element1',
'two is related to element2',
'one is related to element3',
'two is related to element1',
'one is related to element2',
'three is related to element3']
<小时/>

这相当于(简单地打印出这里的字符串):

for l in main_list:
for i,j in zip(l,comparison_list):
print(f'{i} is related to {j}')

关于python - 我的程序在比较两个列表时在 1 次迭代后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58085404/

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