Reputation: 85
I'm trying to split an element of a list within another list where there is whitespace within that element. I have considered using the split() method but I am not sure if it will work for this.
An example of what I am trying to do:
Say I have this list like this:
[['H EL LO', 'h el lo'], ['W OR L D', 'w or l d']...]
I want to turn it into something like this:
[['H', 'EL', 'LO', 'h', 'el', 'lo'], ['W', 'OR', 'L', 'D', 'w', 'or', 'l', 'd']...]
where I can iterate over each "segment" (i.e 'H', 'EL', 'LO' etc) and see if they are in another list for the purpose of my overall function. It doesn't have to look exactly like that, but I just need to be able to iterate over the segments. Note that I don't want to iterate over single characters but rather over the segments, so I thought joining the segments together wouldn't be useful.
How would I do this? Any help would be much appreciated!
Upvotes: 0
Views: 44
Reputation: 512
With
data = [['H EL LO', 'h el lo'], ['W OR L D', 'w or l d']]
You can use some one-liner magic:
print([line.split() for line in [' '.join(group) for group in data]])
You could also do something that might be a bit more readable, if you're unfamiliar with Python:
temporary_list = []
for group in data:
new_group = []
for word in group:
new_group.extend(word.split())
temporary_list.append(new_group)
print(temporary_list)
Upvotes: 1