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"]
6
  • is the output a flat list? the output must be sorted? by individual element? Commented Jun 13, 2019 at 11:53
  • Possible duplicate of Get difference between two lists Commented Jun 13, 2019 at 11:54
  • @AmineMessaoudi this isn't asking for diff, it's merging them Commented Jun 13, 2019 at 11:54
  • it should be merged and no sorting Commented Jun 13, 2019 at 11:56
  • why do you need array of single string? is it comma separated? Commented Jun 13, 2019 at 11:58

4 Answers 4

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']
Sign up to request clarification or add additional context in comments.

Comments

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']

1 Comment

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.
1
[' '.join(element1+element2) for (element1,element2) in zip(in_put_1,in_put_2) ]

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.