1

How to map and append values from one list to other list python 3?

in_put_1 = [["a alphanum2 c d"], ["g h"]] 
in_put_2 = [["e f"], [" i j k"]]

output = ["a alphanum2 c d e f", "g h i j k"]
deceze
  • 510,633
  • 85
  • 743
  • 889
suba
  • 175
  • 1
  • 2
  • 11

4 Answers4

8

You can concatenate the strings in the sublists together while iterating over the two lists together using zip, stripping the individual strings to get rid of surrounding whitespaces in the process

[f'{x[0].strip()} {y[0].strip()}' for x, y in zip(in_put_1, in_put_2)]

To do it without zip, we would need to explicitly use indexes to access elements in the list

result = []
for idx in range(len(in_put_1)):

    s = f'{in_put_1[idx][0].strip()} {in_put_2[idx][0].strip()}'
    result.append(s)

The output will be

['a alphanum2 c d e f', 'g h i j k']
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
4
>>>map(lambda x,y: x[0]+" "+y[0],in_put_1,in_put_2)
['a alphanum2 c d e f', 'g h  i j k']
Kousik
  • 21,485
  • 7
  • 36
  • 59
  • 2
    N.B. In Python 3, `map` returns a generator and needs to be converted to list first before obtaining the output in the form of a list. – TrebledJ Jun 13 '19 at 12:08
1
[' '.join(element1+element2) for (element1,element2) in zip(in_put_1,in_put_2) ]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
horseshoe
  • 1,437
  • 14
  • 42
0
a = [["a alphanum2 c d"], ["g h"]] 
b = [["e f"], [" i j k"]]
c = []
for (a1, b1) in zip(a,b): 
     c.append(''.join([str(a) + b for a,b in zip(a1,b1)]))
print(c)
Maxx Selva K
  • 454
  • 4
  • 9