Home > Mobile >  Get same characters from 2 lists in right order - Python
Get same characters from 2 lists in right order - Python

Time:11-11

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

Example 2:

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

Expected output = - - R -

CodePudding user response:

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

CodePudding user response:

You could do this with a list comprehension making sure you change case to upper and then print by unpacking the list

list_1 = ["r", "w", "d"]
list_2 = ["w", "o", "r", "d"]
print(*[e.upper() if e in list_1 else '-' for e in list_2])

Output:

W - R D

Optionally, unpack a generator:

print(*(e.upper() if e in list_1 else '-' for e in list_2))

CodePudding user response:

Here one solution:

list1 = ["r"]
list2 = ["w", "o", "r", "d"]

for c in list2:
    if c in list1: print(c.upper(), end=' ')
    else: print('-', end=' ')


> Output:
> - - R -
  • Related