0

I have this example :

example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]

So , I want to get the following array:

chars2=[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f','h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's'],['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]

I tried this:

chars2=[]
for list in example:
    for string in list:
        chars2.extend(string)

but i get the following:

['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']
John
  • 9
  • 2

2 Answers2

3

For each list in example you need to add another list inside chars2 , currently you are just extending chars2 directly with each character.

Example -

chars2=[]
for list in example:
    a = []
    chars2.append(a)
    for string in list:
        a.extend(string)

Example/Demo -

>>> example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
>>> chars2=[]
>>> for list in example:
...     a = []
...     chars2.append(a)
...     for string in list:
...         a.extend(string)
...
>>> chars2
[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' '], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

Try using a simple list comprehension

example = [list(item) for sub in example for item in sub]

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76