[英]get items 2 by 2 from a list in Python
What is the most elegant way to obtain items 2 by 2 from a list ? 从列表中以2乘2获得项目的最优雅方法是什么?
from:
my_list = ['I', 'swear', 'I', 'googled', 'first']
to:
res_list = ['I swear', 'swear I', 'I googled', 'googled first']
def window(seq, n=2):
"""
Returns a sliding window (of width n) over data from the sequence
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
for i in xrange(len(seq)-n+1):
yield tuple(seq[i:i+n])
my_list = ['I', 'swear', 'I', 'googled', 'first']
res_list = [' '.join(group) for group in window(my_list, 2)]
print(res_list)
# ['I swear', 'swear I', 'I googled', 'googled first']
I would say a standard case for zip
: 我会说zip
的标准情况:
def pairs(i):
return list(zip(i, i[1:]))
my_list = ['I', 'swear', 'I', 'googled', 'first']
res_list = pairs(my_list)
print(res_list)
# [('I', 'swear'), ('swear', 'I'), ('I', 'googled'), ('googled', 'first')]
print([' '.join(a) for a in res_list])
# ['I swear', 'swear I', 'I googled', 'googled first']
Just for completeness's sake, the same with arbitrary window width: 出于完整性考虑,与任意窗口宽度相同:
def window(i, n = 2):
return list(zip(*(i[p:] for p in range(n))))
def pairwise( iterable, n=2 ):
from itertools import tee, izip, islice
return izip(*(islice(it,pos,None) for pos,it in enumerate(tee(iterable, n))))
my_list = ['I', 'swear', 'I', 'googled', 'first']
print list(pairwise(my_list))
#[('I', 'swear'), ('swear', 'I'), ('I', 'googled'), ('googled', 'first')]
A neat little one-liner in the form of a generator expression: 生成器表达式形式的简洁的单线:
>>> my_list = ['I', 'swear', 'I', 'googled', 'first']
>>> res_list = (' '.join((x, y)) for x, y in zip(my_list, my_list[1:]))
>>> list(res_list)
['I swear', 'swear I', 'I googled', 'googled first']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.