Home > database >  How to Iterate over two lists and position the elements of the output list differently in python pan
How to Iterate over two lists and position the elements of the output list differently in python pan

Time:02-27

How to iterate over two lists such that the output list should have the first value of the first list as the first element, the first value of the second list as the last element, the second value of the first list as the second element, the second value of the second list as the second last element and so on and then remove the duplicates. example: a=['A','C','B','E','D'] b=['B','D','A','E','C']

Output: c=['A','C','E','D','B']

CodePudding user response:

This is a possible solution:

from itertools import zip_longest

lst = [[], []]
s = set()

for t in zip_longest(a, b):
    for i, x in enumerate(t):
        if x is not None and x not in s:
            lst[i].append(x)
            s.add(x)

c = lst[0]   lst[1][::-1]
  • Related