Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Iterate over two lists and position the elements of the output list differently in python pandas?

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading