たとえば、次のようなものです。
>>> [1, 2, 3].contains_sequence([1, 2])
True
>>> [1, 2, 3].contains_sequence([4])
False
in
オペレーターが文字列に対してこれを行うことができることを私は知っています:
>>> "12" in "123"
True
しかし、イテラブルで動作するものを探しています。
たとえば、次のようなものです。
>>> [1, 2, 3].contains_sequence([1, 2])
True
>>> [1, 2, 3].contains_sequence([4])
False
in
オペレーターが文字列に対してこれを行うことができることを私は知っています:
>>> "12" in "123"
True
しかし、イテラブルで動作するものを探しています。
リストを使用するように変更されたhttps://stackoverflow.com/a/6822773/24718から参照。
from itertools import islice
def window(seq, n=2):
"""
Returns a sliding window (of width n) over data from the iterable
s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
"""
it = iter(seq)
result = list(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + [elem]
yield result
def contains_sequence(all_values, seq):
return any(seq == current_seq for current_seq in window(all_values, len(seq)))
test_iterable = [1,2,3]
search_sequence = [1,2]
result = contains_sequence(test_iterable, search_sequence)
Python ビルトインはありますか? いいえ。このタスクはさまざまな方法で実行できます。 これを行うレシピは次のとおりです。また、含まれているシーケンス内のサブシーケンスの位置も示します。
def _search(forward, source, target, start=0, end=None):
"""Naive search for target in source."""
m = len(source)
n = len(target)
if end is None:
end = m
else:
end = min(end, m)
if n == 0 or (end-start) < n:
# target is empty, or longer than source, so obviously can't be found.
return None
if forward:
x = range(start, end-n+1)
else:
x = range(end-n, start-1, -1)
for i in x:
if source[i:i+n] == target:
return i
return None
順序を保持する必要がない場合は、セット(組み込み)を使用できます。
>>> set([1,2]).issubset([1,2,3])
True
>>> set([4]).issubset([1,2,3])
False
さもないと:
def is_subsequence(sub, iterable):
sub_pos, sub_len = 0, len(sub)
for i in iterable:
if i == sub[sub_pos]:
sub_pos += 1
if sub_pos >= sub_len:
return True
else:
sub_pos = 0
return False
>>> is_subsequence([1,2], [0,1,2,3,4])
True
>>> is_subsequence([2,1], [0,1,2,3,4]) # order preserved
False
>>> is_subsequence([1,2,4], [0,1,2,3,4])
False
これはどのイテレータでも機能します。
私の知る限り、これを行う方法はありません。独自の関数を非常に簡単にロールすることができますが、それが非常に効率的であるとは思えません。
>>> def contains_seq(seq,subseq):
... #try: junk=seq[:]
... #except: seq=tuple(seq)
... #try: junk=subseq[:]
... #except: subseq=tuple(subseq)
... ll=len(subseq)
... for i in range(len(seq)-ll): #on python2, use xrange.
... if(seq[i:i+ll] == subseq):
... return True
... return False
...
>>> contains_seq(range(10),range(3)) #True
>>> contains_seq(range(10),[2,3,6]) #False
このソリューションは、ジェネレーター型のオブジェクトでは機能しないことに注意してください (スライスできるオブジェクトでのみ機能します)。seq
続行する前にスライス可能かどうかを確認し、スライスtuple
可能でない場合は a にキャストできますが、スライスの利点がなくなります。スライスを使用する代わりに、一度に 1 つの要素をチェックするように書き直すこともできますが、パフォーマンスがさらに低下すると感じています。
他の人が言ったように、これには組み込みはありません。これは、私が見た他の回答よりも潜在的に効率的な実装です。特に、反復可能なものをスキャンし、見たターゲットシーケンスのプレフィックスサイズを追跡します。しかし、その効率の向上は、提案されている他のいくつかのアプローチよりも冗長性が増すという犠牲を伴います。
def contains_seq(iterable, seq):
"""
Returns true if the iterable contains the given sequence.
"""
# The following clause is optional -- leave it if you want to allow `seq` to
# be an arbitrary iterable; or remove it if `seq` will always be list-like.
if not isinstance(seq, collections.Sequence):
seq = tuple(seq)
if len(seq)==0: return True # corner case
partial_matches = []
for elt in iterable:
# Try extending each of the partial matches by adding the
# next element, if it matches.
partial_matches = [m+1 for m in partial_matches if elt == seq[m]]
# Check if we should start a new partial match
if elt==seq[0]:
partial_matches.append(1)
# Check if we have a complete match (partial_matches will always
# be sorted from highest to lowest, since older partial matches
# come before newer ones).
if partial_matches and partial_matches[0]==len(seq):
return True
# No match found.
return False
dequeはここで役立つようです:
from collections import deque
def contains(it, seq):
seq = deque(seq)
deq = deque(maxlen=len(seq))
for p in it:
deq.append(p)
if deq == seq:
return True
return False
これは、両方の引数に対して任意の反復可能オブジェクトを受け入れることに注意してください(スライスは必要ありません)。
ビルトインがないので、私は素敵なバージョンを作りました:
import itertools as it
def contains(seq, sub):
seq = iter(seq)
o = object()
return any(all(i==j for i,j in zip(sub, it.chain((n,),seq,
(o for i in it.count())))) for n in seq)
これには追加のリストは必要ありませんit.izip
(または Py3kを使用している場合)。
>>> contains([1,2,3], [1,2])
True
>>> contains([1,2,3], [1,2,3])
True
>>> contains([1,2,3], [2,3])
True
>>> contains([1,2,3], [2,3,4])
False
問題なく読めれば加点。(それは仕事をしますが、実装はあまり真剣に受け止めるべきではありません)。;)
それを文字列に変換してから、それを照合することができます
full_list = " ".join([str(x) for x in [1, 2, 3]])
seq = " ".join([str(x) for x in [1, 2]])
seq in full_list