简体   繁体   English

获取列表的连续相邻元素

[英]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? 是否有一种单线或更Python方式实现这一目标?

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

使用zip

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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