0

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!

6
  • 1
    Post 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. Dec 10, 2012 at 20:24
  • 3
    WHat does split not do correctly - let's see your code and the data and the error
    – mmmmmm
    Dec 10, 2012 at 20:24
  • 1
    I'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, 2012 at 20:24
  • 1
    As 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.
    – user166390
    Dec 10, 2012 at 20:25
  • 1
    The answers shouldn't exist yet. It allows OP to do things he probably doesn't understand. Dec 10, 2012 at 20:31

2 Answers 2

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']
3
  • It's probably worth explaining what a list comprehension is. Dec 10, 2012 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. Dec 10, 2012 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. Dec 10, 2012 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']
1
  • 4
    For reference - this is more easily written using from itertools import chain; list(chain.from_iterable(el.split() for el in items)) Dec 10, 2012 at 20:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.