首页 > 解决方案 > 我的程序在 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

标签: pythonlist

解决方案


正如评论中所指出的,错误似乎是您没有重置计数器,因此得到了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}')

推荐阅读