私のコードの共通パターンは次のようなものです: "特定の要素を見つけるまでリストを検索し、それはその前後に来る。リスト内の要素をマッチさせ、その前に `n`個の要素を返し、その後に` m`個の要素を返します
たとえば、重要なイベントにアスタリスクが付いているログファイルを調べ、重要なイベントのコンテキストを取り出すことができます。
Spinning up the hyperdrive
Hyperdrive speed 100 rpm
Hyperdrive speed 200 rpm
Hyperdrive lubricant levels low (100 gal.)
* CRITICAL EXISTENCE FAILURE
Hyperdrive exploded
私は機能が欲しい、get_item_with_context()
、私はアスタリスクで最初の行を見つけることができ、その後、私を与えることを次の例では
、私はハイパードライブが爆発なぜを知りたいですその前にはn
行まで続き、それに続く行はm
行です。
私の試みは、以下の通りです:これで
>>> get_item_with_context(lambda x: x == 3, [1,2,3,4,5,6],
items_before = 1, items_after = 1)
[2, 3, 4]
問題:not(predicate(d[-1]))
を使用して、我々は実際に試合を発見したことを確認するチェック
-
import collections, itertools def get_item_with_context(predicate, iterable, items_before = 0, items_after = 0): # Searches through the list of `items` until an item matching `predicate` is found. # Then return that item. # If no item matching predicate is found, return None. # Optionally, also return up to `items_before` items preceding the target, and # `items after` items after the target. # # Note: d = collections.deque (maxlen = items_before + 1 + items_after) iter1 = iterable.__iter__() iter2 = itertools.takewhile(lambda x: not(predicate(x)), iter1) d.extend(iter2) # zero-length input, or no matching item if len(d) == 0 or not(predicate(d[-1])): return None # get context after match: try: for i in xrange(items_after): d.append(iter1.next()) except StopIteration: pass if (items_before == 0 and items_after == 0): return d[0] else: return list(d)
使い方は次のようにする必要があります何らかの理由で動作しません。常にfalseを返します。
- 一致するアイテムが見つかった後にリストに
items_after
個未満のアイテムがある場合、結果はごみです。 - 他のエッジケース?
私はこの作業を行う方法/より頑強にするためのアドバイスをしてもらえますか?あるいは、私が車輪を再発明しているなら、それも私に教えてください。
これはスライシングでは達成できないものですか? –
@BurhanKhalid:巻き戻しできないイテラブルを使用している可能性があります。 –
なぜiterable .__ iter __() 'の代わりに' iterable .__ iter __() 'を使用しますか? – jamylak