如何在python中的同一for循环中遍历两个长度不同的列表?

时间:2018-12-17 10:57:33

标签: python-3.x

输入列表:

input1 = ['A,B,C,D,E',
'"111","112","113","114","115"',
'"211","212","213","214","215"']

input2 = ['A,B,C,D,E',
'"111","112","113","114","115"',
'"211","212","213","214","215"',
'"311","312","313","314","315"',]

output = ['A,B,C,D,E',
'"111","112","113","114","115"',
'"211","212","213","214","215"',
'"311","312","313","314","315"',]

输出应具有两个中的所有条目...

for line1, line2 in zip(input1,input2):
    temp1 = line1.split(',')
    temp2 = line2.split(',')

在上面的代码中,两个列表的长度都不同。...我还要迭代直到两个列表中最长的列表的结尾

我试图找到答案,但无法如此。

1 个答案:

答案 0 :(得分:0)

遍历更大的列表并将每个元素存储到哈希表中会更有效率。然后遍历第二个列表,并确定身份密钥与上一个元素匹配的位置。打印发现重复的每一个。您当前的方法将必须遍历每个元素的列表,从而导致O(n 2 )的二次时间复杂度,而使用哈希表应获得O(n * log(n)

哈希表:

1。)https://www.tutorialspoint.com/python/python_hash_table.htm

2。)http://interactivepython.org/runestone/static/pythonds/SortSearch/Hashing.html