Python 获取列表中连续的相邻元素
我希望从列表中创建连续的单词序列组合Python 获取列表中连续的相邻元素,python,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', 'natur
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.']
我猜下面的代码效率不高。有没有一种简单的方法或者更像蟒蛇的方法来实现这一点
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.')]
使用
zip
:
wordseq = zip(news,news[1:])
您可以使用
zip(news[:-1],news[1:])
可能重复的why[:-1]
?没有必要。为了让它更好,我会使用itertools.izip
和itertools.islice
。这将提高速度和内存使用率。zip
本身在Python3中是可以使用的<代码>islice仍然存在。
wordseq = [(news[i-1], news[i]) for i in range(1, len(news))]