简体   繁体   中英

How to return every nth item in a list for Python?

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.

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'

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
[word for item in list1 for word in item.split()][0::3]

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'

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'
>>>>

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM