簡體   English   中英

從Python列表中獲得2乘2的項

[英]get items 2 by 2 from a list in Python

從列表中以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']

我會說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))))
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')]

生成器表達式形式的簡潔的單線:

>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM