Reputation: 1311
What is the most elegant way to obtain items 2 by 2 from a list ?
from:
my_list = ['I', 'swear', 'I', 'googled', 'first']
to:
res_list = ['I swear', 'swear I', 'I googled', 'googled first']
Upvotes: 1
Views: 488
Reputation: 4243
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)))
output:
['I swear', 'I googled', 'first']
Upvotes: 0
Reputation: 20361
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']
Upvotes: 0
Reputation: 879591
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']
Upvotes: 5
Reputation: 32429
I would say a standard case for 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))))
Upvotes: 1
Reputation: 13539
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')]
Upvotes: 1