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

Get same characters from 2 lists in right order – Python

I have two lists and I need to print matching characters to string in order of characters in list 2. If there is no match, i need to print "-" instead of that character. Final string should have same length of chars as list 2

Example 1 :

list 1 = ["r", "w", "d"]
list 2 = ["w", "o", "r", "d"]

Expected output = W – R D

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

Example 2:

list 1 = ["r"]
list 2 = ["w", "o", "r", "d"]

Expected output = – – R –

>Solution :

You can use list comprehension to check if the character in actual word (list2) is present in the list1 or not –

list1 = ["r", "w", "d"]
list2 = ["w", "o", "r", "d"]
print(' '.join([i.upper() if i in list1 else '-' for i in list2]))

Output –

W - R D

You can optionally create a set from list1 for faster lookup in case the word lengths are huge –

given_words = set(list1)
print(' '.join([i.upper() if i in given_words else '-' for i in list2]))
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