HackersInside
HackersInside

Reputation: 307

Conditional Merging of Lists

I'm trying to merge two lists based on the following rules:

The first element in list1 should be merged with the last element in list2, the second element in list1 should be merged with second last element in list2 and so on.

If an element in list1/list2 is None, then the corresponding element in the other list should be kept as it is in the merged list.

I feel I may have to use a linked list here, but I'm not sure. I'm trying to figure out the solution by looping over the lists, but I'm not able to figure out the logic here.

def merge_list(list1, list2):
    merged_data=""
    new_str=""
    #write your logic here
    for l1 in list1:
        for l2 in list2[::-1]:
            if l1 is None or l2 is None:
                pass
            else:
                new_str = l1+l2
                i=list2.index(l2)
                print(new_str)
            break
    #return resultant_data


list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
merged_data=merge_list(list1,list2)
print(merged_data)

Expected Output:

“An apple a day keeps the doctor away”

Upvotes: 0

Views: 4594

Answers (10)

Babu Reddy
Babu Reddy

Reputation: 1

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
s=''
new=''
for i in list1:
    for j in list2[::-1]:
        if i==None:
            i=''
        elif j==None:
            j=''
        new=i+j
        s=s+new+' '
        list2.pop(-1)
        break
print(s)

Upvotes: 0

Kalpan Shah
Kalpan Shah

Reputation: 1

def merge_list(list1, list2):
merged_data = ""
list3 = list1   
for i in range(1, 2*len(list2) + 1,2):    #Converting both lists in single list
    list3.insert(i, list2[-1])    # Adding last elements of list2 at alternate to positions elements of list3
    list2.pop()  #Removing the last element from list2
list3 = ["" if i is None else i for i in list3]   # Handling NoneType condition. If there is "None", convertted to ""
for i in range(0,len(list3),2):
    word="".join(list3[i:i+2])   #joining the elements in set of two
    merged_data=merged_data+word+" "   #converting above word into one
return merged_data

Upvotes: 0

Mohan Kumar
Mohan Kumar

Reputation: 1

l1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
l2=['y','tor','e','eps','ay',None,'le','n']
a=l2[::-1]
l3=[]
for i in range(len(l1)):
    if(l1[i] is None or a[i] is None):
        l3.append(l1[i])`enter code here`
    else:
        l3.append(l1[i]+a[i])


print(" ".join(l3))

Upvotes: 0

khushbu jindal
khushbu jindal

Reputation: 1

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
a=list2.remove(None)
list2.insert(5,"")
list3 = [ str(x[0]) + x[1]   for x in zip(list1, list2[::-1]) ]
print ' '.join(list3)

output:

An apple a day keeps the doctor away

Upvotes: 0

Bitto
Bitto

Reputation: 8205

A short answer without using zip.

" ".join([list1[x]+[y if y is not None else '' for y in list2 ][::-1][x] for x in range(len(list1)-1)]

Upvotes: 0

Vishal
Vishal

Reputation: 1

def fetch_index(list2, item_index):
    x = list2[::-1]
    return x[item_index]

def merge_list(list1, list2):
    list_3 = []
    #write your logic here
    for l1 in list1:
        l2 = fetch_index(list2, list1.index(l1))
        if l1 is None and l2 is None:
            pass
        elif l1 is None:
            list_3.append(l2)
        elif l2 is None:
            list_3.append(l1)
        else:
            list_3.append(l1+l2)
    return(list_3)

list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2=['y','tor','e','eps','ay',None,'le','n']
x = merge_list(list1,list2)
print ' '.join(i for i in x)

A longer version if you don't want to use zip

Upvotes: 0

Austin
Austin

Reputation: 26039

You can use zip to iterate through two lists simultaneously:

def merge_list(lst1,lst2):
    s = ''
    for x, y in zip(lst1, lst2[::-1]):
        if y and x:
            s += x + y
        elif x:
            s += x
        elif y:
            s += y
        s += ' '
    return s[:-1]

list1 = ['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
list2 = ['y','tor','e','eps','ay',None,'le','n']
merged_data = merge_list(list1,list2)

print(merged_data)
# An apple a day keeps the doctor away

You can shorten this and use a list-comprehension, like below (but, I would prefer the other which is more readable):

def merge_list(lst1,lst2):
    return ' '.join(x + y if x and y else x if x else y for x, y in zip(lst1, lst2[::-1]))

Upvotes: 2

cph_sto
cph_sto

Reputation: 7585

First use list comprehensions to merge the two lists and then convert that list into string.

" ".join(str(x) for x in [list1[i]+list2[len(list2)-1-i] if list2[len(list2)-1-i] != None else list1[i] for i in range(len(list1))])
    'An apple a day keeps the doctor away'

Upvotes: 0

hunzter
hunzter

Reputation: 598

Make sure the lists are in same length then just a zip is enough. But replace None value with '' (empty string)

["".join(row) for row in zip(list1, reversed(list2))]

=>

['An', 'apple', 'a', 'day', 'keeps', 'the', 'doctor', 'away']

Upvotes: 0

caverac
caverac

Reputation: 1637

Assuming both lists have the same length

>>> list1=['A', 'app','a', 'd', 'ke', 'th', 'doc', 'awa']
>>> list2=['y','tor','e','eps','ay',None,'le','n']
>>> ' '.join([l1 + l2 if l1 and l2 else l1 if l1 and not l2 else l2 for l1, l2 in zip(list1, reversed(list2)) if l1 and l2])
'An apple a day keeps the doctor away'

Upvotes: 0

Related Questions