获取列表的连续相邻元素

时间:2014-08-06 05:47:03

标签: python

我希望从列表中创建连续的单词序列组合。

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

我猜以下代码效率不高。是否有单线或更加pythonic的方式实现这一目标?

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

我想要的结果就是这个;

[('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.')]

3 个答案:

答案 0 :(得分:3)

使用zip

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

答案 1 :(得分:3)

您可以使用zip(news[:-1], news[1:])

答案 2 :(得分:1)

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