Reputation: 11
Suppose, I have a list like the following:
names= ["my name xyz","your name is abc","her name is cfg zyx"]
I want to split them like following:
my_array[0]= ["my","name","xyz"]
my_arrray[1]= ["your","name","is","abc"]
my_array[2]= ["her","name","is","cfg","zyx"]
So that I can choose the words individually like following:
my_array[0][0]= my
my_array[0][1]= name
my_array[1][2]= is
my_array[0][2]= xyz
The python code i tried is following:
names_abc= names.splitlines(True)
#print(names_abc)
i=0
while i < len(names_abc):
my_array= names_abc[i].split()
print(my_array[0])
i=i+1
But this code doesn't do what I expect. It splits the list but cannot choose the words individually. For example, the output of the above code is following:
my your her
which is definitely wrong. I will be grateful to get a help from the python experts. Thanks in advance.
Upvotes: 1
Views: 11895
Reputation: 880827
You could define my_array
using a list comprehension:
my_array = [phrase.split() for phrase in names]
which is equivalent to
my_array = list()
for phrase in names:
my_array.append(phrase.split())
Demo:
In [21]: names= ["my name xyz","your name is abc","her name is cfg zyx"]
In [22]: my_array = [phrase.split() for phrase in names]
In [23]: my_array
Out[23]:
[['my', 'name', 'xyz'],
['your', 'name', 'is', 'abc'],
['her', 'name', 'is', 'cfg', 'zyx']]
In [24]: my_array[0][1]
Out[24]: 'name'
One problem with defining my_array
this way:
while i < len(names_abc):
my_array= names_abc[i].split()
is that my_array
is assigned to a new list each time through the while-loop
. So my_array
does not become a list of lists. Instead, after the while-loop
, it only retains its last value.
Instead of printing my_array[0]
, try print(my_array)
itself. It might become more clear why you're getting the result you were getting.
Upvotes: 5
Reputation: 19
I would create a new list and fill it with lists containing temporaray strings build from the characters of your starting list.
The temporary string is ended by the space, when a string is complete it is added to a temoprary list (list_tmp).
After all items are processed as strings and added to the temporary list, we append that list the final list:
a=["my name xyz","your name is abc","her name is cfg zyx"]
l=[]
for i in enumerate(a):
tmp_str = ''
list_tmp=[]
for j in i[1]:
if " " in j:
list_tmp.append(tmp_str)
tmp_str=''
else:
tmp_str+=j
else:
list_tmp.append(tmp_str)
l.append(list_tmp)
print l
print l[0][1]
Upvotes: 0
Reputation: 118011
You could split()
every element in your list, which by default will split on spaces.
>>> names= ["my name xyz","your name is abc","her name is cfg zyx"]
>>> [i.split() for i in names]
[['my', 'name', 'xyz'], ['your', 'name', 'is', 'abc'], ['her', 'name', 'is', 'cfg', 'zyx']]
Upvotes: 2