从列表中获取2项2的最优雅方式是什么?
from:
my_list = ['I', 'swear', 'I', 'googled', 'first']
to:
res_list = ['I swear', 'swear I', 'I googled', 'googled first']
答案 0 :(得分:5)
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']
答案 1 :(得分:1)
我会说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']
为了完整起见,与任意窗口宽度相同:
def window(i, n = 2):
return list(zip(*(i[p:] for p in range(n))))
答案 2 :(得分:1)
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')]
答案 3 :(得分:0)
生成器表达形式的整齐的小单线:
>>> 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']
答案 4 :(得分:0)
my_list = ['I', 'swear', 'I', 'googled', 'first']
def two_words(my_list):
i=0
words=[]
for word in my_list:
words.append(word)
if i%2:
yield (" ".join(words))
words.clear()
i+=1
if len(words)>0:
yield (" ".join(words))
print(list(two_words(my_list)))
输出:
['I swear', 'I googled', 'first']