I've got a list that contains a url and some text in each item of a large list in Python. I'd like to split each item in several items every time a space appears (2-3 spaces per item). There isn't much code to post, its just a list stored in a named variable at the moment. I've tried using the split function but I just can't seem to get it right. Any help would be greatly appreciated!
Asked
Active
Viewed 4.9k times
0
-
1Post your current code. It at least shows you have made some effort to solve it yourself, and it's far easier to see what your data structure is with an example over a textual description. – Gareth Latty Dec 10 '12 at 20:24
-
3WHat does split not do correctly - let's see your code and the data and the error – mmmmmm Dec 10 '12 at 20:24
-
1I'm not quite certain what your input is. Is it a list of a list? A list of strings? It would help a lot of you'd just include an example list, like `input_list = [...]`. – phihag Dec 10 '12 at 20:24
-
1As well as posting current code (which is always a good start), also post the input and desired output. Since there is current code (nudge, nudge), also provide any incorrect output, as apporpriate. – Dec 10 '12 at 20:25
-
1The answers shouldn't exist yet. It allows OP to do things he probably doesn't understand. – Markus Unterwaditzer Dec 10 '12 at 20:31
-
@Lattyware, @phihag, @Mark, @pst `probs = soup.findAll('table',{'class':'prob'}) for x in probs: new_probs.append(x.split(' '))` This is currently what I have. Each element in the list `probs` looks something to the effect of ['url (space) text (space) text']. I'd like to take each element in the list and split them at the spaces, thereby lengthening the list to three times what it currently is. I just can't seem to get it working with the code I have above. – Arc' Dec 10 '12 at 22:31
2 Answers
12
It's hard to know what you're asking for but I'll give it a shot.
>>> a = ['this is', 'a', 'list with spaces']
>>> [words for segments in a for words in segments.split()]
['this', 'is', 'a', 'list', 'with', 'spaces']

Mark Ransom
- 299,747
- 42
- 398
- 622
-
It's probably worth explaining what a [list comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw) is. – Gareth Latty Dec 10 '12 at 20:36
-
@Lattyware, you're right, thanks for adding the link. And this isn't the simplest example of one either - it took me a couple of tries to get it right. – Mark Ransom Dec 10 '12 at 20:42
-
The multiple loop ones are always fun. I'd probably have gone for a use of `itertools.chain.from_iterable()` myself to avoid it. – Gareth Latty Dec 10 '12 at 20:44
1
You can try something like that:
>>> items = ['foo bar', 'baz', 'bak foo bar']
>>> new_items = []
>>> for item in items:
... new_items.extend(item.split())
...
>>> new_items
['foo', 'bar', 'baz', 'bak', 'foo', 'bar']

ank
- 106
- 5
-
4For reference - this is more easily written using `from itertools import chain; list(chain.from_iterable(el.split() for el in items))` – Jon Clements Dec 10 '12 at 20:33