python - 我的程序在 1 次迭代后停止,同时比较两个列表
问题描述
我有一个函数,它需要一个主列表,里面有 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}')
推荐阅读
- c# - 打开文件夹中的所有word文档并替换word。此应用程序在打开 5 个文档后卡住
- php - 如何制作 where 语句 = 一个 php 会话变量
- amazon-web-services - 在解码 JWT 时,从 AWS 机密管理器中检索机密会导致问题
- expo - 使用 expo branch.io SDK 和广告合作伙伴链接安装归因
- admin - 为什么我不能成为 Telegram 的管理员?
- react-navigation - 在navigation.goback() 之后需要返回吗?
- c# - 当我们有支持 OOP 概念的类和接口时,为什么 C# 支持结构
- java - MetricRegistry 的可序列化类中的非瞬态不可序列化实例字段
- python - 一种将函数循环到自身的pythonic方法
- objective-c - XCode - 如何在共享扩展中包含 React Native 库?