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']
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))))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句