Is there any way to add this two array to get a new list in python

Viewed 33

I want to simulate a left outer join of these two arrays array = ['a', 'b','c', 'd', 'e'] array2 = ['a', 'a', 'f', 'g', 'b'] which the results will be as follows. opt = ['aa', 'aa', ,'bb','c_', 'd_', 'e_']

2 Answers

The question was a bit ambiguous as the comments have pointed out.

But it appears from the question that you are trying to get all the combinations (and not just add the two lists)...

If this is the case then nested for loops (or list comprehension) are two basic methods:

array = ['a', 'b', 'c', 'd', 'e'] 
array2 =['a', 'a', 'f', 'g', 'b'] 

all = []
for i in array:
    for j in array2:
        all.append(i+j)


print(all)

returns this:

['aa', 'aa', 'af', 'ag', 'ab', 'ba', 'ba', 'bf', 'bg', 'bb', 'ca', 'ca', 'cf', 'cg', 'cb', 'da', 'da', 'df', 'dg', 'db', 'ea', 'ea', 'ef', 'eg', 'eb']

If you are combining the lists then this would work:

array = ['a', 'b','c', 'd', 'e'] 
array2 =['a', 'a', 'f', 'g', 'b'] 

length = len(array)

new = []
for i in range(length):
    # some rules here
    v = array[i] + array2[i]
    new.append(v)

new

which gives this:

['aa', 'ba', 'cf', 'dg', 'eb']

In both cases, you can add rules in the (nested) for loops.

If you want to do an outer left join this might work:

array = ['a', 'b', 'c', 'd', 'e']
array2 =  ['a', 'a', 'f', 'g', 'b']
array3 = []
for i in array:
 subarray = []
 for j in array2:
  if i == j: 
   subarray.append(i+j)
  else: 
   subarray.append(i+"_")
 if any([n[1] != "_" for n in subarray]):
  for n in subarray:
   if n[1] != "_":
    array3.append(n)
 else:
  array3.append(i + "_")
Related