本文介绍了在列表中查找连续值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个值列表:
a = [1,3,4,5,2]
我现在想要以下功能:
does_segment_exist(a, [1,3,4]) #True
does_segment_exist(a, [3,4,5]) #True
does_segment_exist(a, [4,5,2]) #True
does_segment_exist(a, [1,4,5]) #False
does_segment_exist(a, [1,3]) #True
does_segment_exist(a, [1,4]) #False
因此必须按连续顺序找到值.
So the values must be found in consecutive order.
我在Python 3中有一个聪明的方法吗?
I there a clever way of doing this in Python 3?
推荐答案
您可以使用滚动窗口迭代器,在这种情况下,它来自itertools
文档的旧版本:
You can use a rolling window iterator, in this case one from an old version of the itertools
docs:
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 = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def does_segment_exist(iterable, sublist):
return tuple(sublist) in window(iterable, len(sublist))
print(does_segment_exist([1,3,4,5,2], [3,4,5]))
如果您只需要它来处理列表,而不需要任何迭代,则可以使用:
If you only need it to work on lists, not any iterable, you can use:
def does_segment_exist(seq, sublist):
# seq and sublist must both be lists
n = len(sublist)
return sublist in (seq[i:i+n] for i in range(len(seq) + 1 - n))
Raymond提到的方法的基本实现:
A basic implementation of the method mentioned by Raymond:
def does_segment_exist(seq, sublist):
first = sublist[0]
i = 0
n = len(sublist)
while True:
try:
i = seq.index(first, i)
except ValueError:
return False
if sublist == seq[i:i+n]:
return True
i += 1
print(does_segment_exist([1,3,4,5,2], [3,4,5]))
此方法的优点是,不必为直到第一个匹配项的每个索引切片,而只需对与该段中第一个值的匹配项对应的索引进行切片.
The advantage of this method is that it doesn't have to slice for every index up to the first match, just for indexes corresponding to matches for the first value in the segment.
这篇关于在列表中查找连续值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!