Skip to content Skip to sidebar Skip to footer

Concatenate Two Strings That Are In Different Lists

I need to concatenate two strings that are in different lists and check if the output string is in a dictionary. The code I've tried is: x=['casa','lo','pre','computer'] y=['music'

Solution 1:

IIUC then you can use itertools.product to get product of two different lists and then perform set intersection to find the common words

from itertools import product
x=['casa','lo','pre','computer']
y=['music','sun','ve','sident','house']
dic=['sunday','love','president','house','computer']
set(list(map(''.join, list(product(x, y)))) + x + y) & set(dic)

OUTPUT:

{'computer', 'house', 'love', 'president'}

If the expected output should not include house from second list then do not append list y in the final concatenated list

set(list(map(''.join, list(product(x, y)))) + x) & set(dic)

OUTPUT

{'computer', 'love', 'president'}

Solution 2:

With your approach, you need to reset the iterator over y each time you try a new value in x.

It might be clearer like this:

for i in x:if i in dic:text.append(i)else:for j in y:concatenated=i+jif concatenated in dic:text.append(concatenated)

The for j in y tries all the things in y, otherwise it moves on each time, and never looks back.

Solution 3:

For a one liner use filter , ''.join and add [''] to the second list (so you don't have to do two ifs):

list(filter(lambda i: i in dic, [''.join((s1, s2)) for s1 in x for s2 in (y + [''])]))
>>['love', 'president', 'computer']

Solution 4:

Does this work for you?

x=['casa','lo','pre','computer']
y=['music','sun','ve','sident','house']
dic=['sunday','love','president','house','computer']

possibles = []
possibles += x
possibles += y # if you want the house...

hits = []
forain x:
    forbin y:
        possibles.append(a+b)
forain y:
    forbin x:
        possibles.append(a+b)

forpin possibles:
    if p in dic:
        hits.append(p)

print(p)

Solution 5:

Here's a straightforward version with nothing fancy. Others have suggested options that are likely more efficient; however, I think this solution captures your desired solution better than some (e.g., by checking all variations of concatenations).

You will want to use sets if you're doing a lot of lookups.

x = ['casa','lo','pre','computer']
y = ['music','sun','ve','sident','house']
dic = set(['sunday','love','president','house','computer'])
in_dic = set()
for str in y:
    if str in dic:
        in_dic.add(str)
for str1 in x:
    if str1 in dic:
        in_dic.add(str1)
    for str2 in y:
        str3 = str1 + str2
        str4 = str2 + str1
        if str3 in dic:
            in_dic.add(str3)
        if str4 in dic:
            in_dic.add(str4)

print(list(in_dic))
['president', 'love', 'computer', 'house']

Post a Comment for "Concatenate Two Strings That Are In Different Lists"