richie
richie

Reputation: 18638

getting successive adjacent elements of a list

I'm looking to create successive word sequence combinations from a list.

news = ['Brendan', 'Rodgers', 'has', 'wasted', 'no', 'time', 'in', 'playing', 'mind', '
games', 'with', 'Louis', 'van', 'Gaal', 'by', 'warning', 'the', 'new', 'Manchest
er', 'United', 'manager', 'that', 'the', 'competitive', 'nature', 'of', 'the', '
Premier', 'League', 'will', 'make', 'it', 'extremely', 'difficult', 'for', 'the'
, 'Dutchman', 'to', 'win', 'the', 'title', 'in', 'his', 'first', 'season.']

The following code I guess is not efficient. Is there a one-liner or a more pythonic way of achieving this?

wordseq = []
for i,j in enumerate(news):
    if len(news)-1 != i:
        wordseq.append((j, news[i+1]))

The result I want is this;

[('Brendan', 'Rodgers'), ('Rodgers', 'has'), ('has', 'wasted'), ('wasted', 'no')
, ('no', 'time'), ('time', 'in'), ('in', 'playing'), ('playing', 'mind'), ('mind
', 'games'), ('games', 'with'), ('with', 'Louis'), ('Louis', 'van'), ('van', 'Ga
al'), ('Gaal', 'by'), ('by', 'warning'), ('warning', 'the'), ('the', 'new'), ('n
ew', 'Manchester'), ('Manchester', 'United'), ('United', 'manager'), ('manager',
 'that'), ('that', 'the'), ('the', 'competitive'), ('competitive', 'nature'), ('
nature', 'of'), ('of', 'the'), ('the', 'Premier'), ('Premier', 'League'), ('Leag
ue', 'will'), ('will', 'make'), ('make', 'it'), ('it', 'extremely'), ('extremely
', 'difficult'), ('difficult', 'for'), ('for', 'the'), ('the', 'Dutchman'), ('Du
tchman', 'to'), ('to', 'win'), ('win', 'the'), ('the', 'title'), ('title', 'in')
, ('in', 'his'), ('his', 'first'), ('first', 'season.'), ('Brendan', 'Rodgers'),
 ('Rodgers', 'has'), ('has', 'wasted'), ('wasted', 'no'), ('no', 'time'), ('time
', 'in'), ('in', 'playing'), ('playing', 'mind'), ('mind', 'games'), ('games', '
with'), ('with', 'Louis'), ('Louis', 'van'), ('van', 'Gaal'), ('Gaal', 'by'), ('
by', 'warning'), ('warning', 'the'), ('the', 'new'), ('new', 'Manchester'), ('Ma
nchester', 'United'), ('United', 'manager'), ('manager', 'that'), ('that', 'the'
), ('the', 'competitive'), ('competitive', 'nature'), ('nature', 'of'), ('of', '
the'), ('the', 'Premier'), ('Premier', 'League'), ('League', 'will'), ('will', '
make'), ('make', 'it'), ('it', 'extremely'), ('extremely', 'difficult'), ('diffi
cult', 'for'), ('for', 'the'), ('the', 'Dutchman'), ('Dutchman', 'to'), ('to', '
win'), ('win', 'the'), ('the', 'title'), ('title', 'in'), ('in', 'his'), ('his',
 'first'), ('first', 'season.')]

Upvotes: 0

Views: 135

Answers (3)

dexter
dexter

Reputation: 141

wordseq = [(news[i-1], news[i]) for i in range(1, len(news))]

Upvotes: 1

BlackMamba
BlackMamba

Reputation: 10254

You can use zip(news[:-1], news[1:])

Upvotes: 3

WeaselFox
WeaselFox

Reputation: 7380

using zip:

wordseq = zip(news,news[1:])

Upvotes: 3

Related Questions