Home > Enterprise >  How to merge two lists, each list contains integer and strings, and I need to do the calculation to
How to merge two lists, each list contains integer and strings, and I need to do the calculation to

Time:01-18

When I practising Python, I have two lists:

list_a = [1, 'a', 'c', 'e', 'f'] 
list_b = [2, 'b', 'c', 'd', 'e'] 

and I want the output is:

list_c = [3, 'a','b','c','d','e','f']

I tried:

list_c = [x   y for (x, y) in zip(list_a, list_b)] 

the output is:

[3, 'ab', 'cc', 'ed', 'fe']

I also tried:

list_c = set(list_a   list_b)

the output is:

{1, 2, 'a', 'b', 'c', 'd', 'e', 'f'}

Can someone know how to do it? And the real output is like this:

list_c = [3, 'a','b','c','d','e','f']

Thanks.

CodePudding user response:

This is an option for your example but I'm not really sure what you want.

list_a = [1, 'a', 'c', 'e', 'f']
list_b = [2, 'b', 'c', 'd', 'e']

def merge(a,b):
    result=[]
    for (r,p) in zip(a,b):
        if(type(r) == type(p)):
            if type(r)==int:
                result.append(str(r p))
            else:
                result.append(r)
                result.append(p)
        else:
            result.append(r)
            result.append(p)
    result = list(set(result))
    result.sort()
    for n,k in enumerate(result):
        try:
            result[n] = int(k)
        except:
            pass
    return(result)

print(merge(list_a,list_b))

Prints:[3, 'a', 'b', 'c', 'd', 'e', 'f']

  •  Tags:  
  • Related