我的程序在1次迭代后停止,同时比较了两个列表

时间:2019-09-24 17:25:07

标签: python list

我有一个接受主列表的函数,里面有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

1 个答案:

答案 0 :(得分:1)

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