Reputation: 29
I have a list that is in a similar format as this:
list1 = ['random words go', 'here and','the length varies','blah',
'i am so confused', 'lala lala la']
What code would be appropriate to return every 3rd item of the list, including the first word? This is the expected output:
["random", "here", "length", "i", "confused", "la"]
I am thinking that I should use the split function, but I don't know how to do this. Can someone also explain how I can make it so the whole list isn't in 'parts' like that? Rather, how can I turn it into one long list, if that makes sense.
Upvotes: 2
Views: 2170
Reputation: 10506
Try this:
>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la']
>>> result = ' '.join(list1).split()[::3]
['random', 'here', 'length', 'i', 'confused', 'la']
Upvotes: 0
Reputation: 63
To turn it into one long list:
>>> list6 = []
>>> for s in list1:
... for word in s.split():
... list6.append(word)
...
>>> list6
['random', 'words', 'go', 'here', 'and', 'the', 'length', 'varies', 'blah', 'i', 'am', 'so', 'confused', 'lala', 'lala', 'la']
>>>
Then you can do the slicing as suggested with [::3]
>>> list6[::3]
['random', 'here', 'length', 'i', 'confused', 'la']
If you want it in one string:
>>> ' '.join(list6[::3])
'random here length i confused la'
>>>>
Upvotes: 0
Reputation: 142136
Go for:
list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la']
from itertools import chain, islice
sentence = ' '.join(islice(chain.from_iterable(el.split() for el in list1), None, None, 3))
# random here length i confused la
Upvotes: 3
Reputation: 304137
Another memory efficient version
>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la']
>>> from itertools import chain, islice
>>> ' '.join(islice(chain.from_iterable(map(str.split, list1)), 0, None, 3))
'random here length i confused la'
Upvotes: 0
Reputation: 69012
This is probably the most readable way to do it:
>>> list1 = ['random words go', 'here and','the length varies','blah', 'i am so confused', 'lala lala la']
>>> result = ' '.join(list1).split()[::3]
['random', 'here', 'length', 'i', 'confused', 'la']
or without joining and splitting the list again:
from itertools import chain
result = list(chain.from_iterable(s.split() for s in list1))[::3]
then you can just join the result:
>>> ' '.join(result)
'random here length i confused la'
Upvotes: 6