0

I have a string:

[('I', 'PRP'), ('have', 'VBP'), ('lost', 'VBN'), ('a', 'DT'), ('pant', 'NN')]

Now I need to take the words in between single quotes in an array. as example:

 array1[0] = I 
 array1[1] = PRP 
 array1[2] = have 
 array1[3] = VBP
 And so on ... 

The number of entries [assuming ('x', 'y') makes an entry] is variable in the original string. And the array needs to be a string array, not something like numpy ndarray. Now, how to do that with Python?

I also have a List object just like the original string. If the same result can be achieved by processing the list object, that would also work fine.

nsssayom
  • 364
  • 1
  • 5
  • 21
  • You have a list of tuples you need a nested loop to access the inner values – Joe Jul 23 '17 at 18:07
  • The thing in your 1st codeblock is a list of tuples of strings. The arrays provided by the Python [`array`](https://docs.python.org/3/library/array.html) module are primarily designed to handle numerical data; they can be used to create arrays of chars, but not arrays of strings. I don't understand why you can't just construct a [list](https://docs.python.org/3/library/stdtypes.html#list) of strings. – PM 2Ring Jul 23 '17 at 18:10

2 Answers2

2
from itertools import chain

result = list(chain.from_iterable(your_list))

chain.from_iterable does exactly what you'd think it does: it flattens the given iterable (converts nested structure into a chain).

ForceBru
  • 43,482
  • 10
  • 63
  • 98
2

It's same like make list of list into a single list,

In [3]: lst = [('I', 'PRP'), ('have', 'VBP'), ('lost', 'VBN'), ('a', 'DT'), ('pant', 'NN')]
In [4]: print [i for j in lst for i in j]
Out[4]: ['I', 'PRP', 'have', 'VBP', 'lost', 'VBN', 'a', 'DT', 'pant', 'NN']
Rahul K P
  • 15,740
  • 4
  • 35
  • 52