2016-04-13 7 views
3

この質問はこの他のSlicing a list into a list of sub-listsと似ていますが、私の場合、前の各サブリストの最後の要素を次のサブ-リスト。そして、最後の要素は、少なくとも二つの要素Pythonリストを重なり合ったチャンクのリストに分割する

などを持って、常に持っていることを考慮に入れる必要があります:

list_ = ['a','b','c','d','e','f','g','h'] 

結果をサイズ3サブリストのために:

resultant_list = [['a','b','c'],['c','d','e'],['e','f','g'],['g','h']] 

答えて

7
>>> list_ = ['a','b','c','d','e','f','g','h'] 
>>> n = 3 # group size 
>>> m = 1 # overlap size 
>>> [list_[i:i+n-m+1] for i in xrange(0,len(list_), n-m)] 
[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h']] 
2
[list_[i:i+n] for i in xrange(0,len(list_), n-m)] 
+2

解決策を説明してください。 –

+0

トップの回答にはリストの理解にバグがあり、予期しない動作につながった。私は、その特定の行に対してより良い解決策であると感じたものを提供しました。 'list_ [i:i + n-m + 1]'は、この解決策を見ているほとんどの人にはおそらく望ましくないものです。 – user3695978

2

more_itertoolsには繰り返し可能なオーバーラップ用のウィンドウツールがあります。

考える

import more_itertools as mit 

iterable = list("abcdefgh") 
iterable 
# ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 

コード

windows = list(mit.windowed(iterable, n=3, step=2)) 
windows 
# [('a', 'b', 'c'), ('c', 'd', 'e'), ('e', 'f', 'g'), ('g', 'h', None)] 

必要な場合は、WindowsをフィルタリングすることによりNone fillvalueをドロップすることができます。

[list(filter(None, w)) for w in windows] 
# [['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h']] 

のSeまた、more_itertools docsの詳細については、more_itertools.windowed

関連する問題