给定一个包含噪声包围的已知模式的列表,是否有一种优雅的方法可以获得与模式相同的所有项目。请参阅下面的原始代码。
list_with_noise = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5]
known_pattern = [1,2,3,4]
res = []
for i in list_with_noise:
for j in known_pattern:
if i == j:
res.append(i)
continue
print res
我们会得到2, 1, 2, 3, 4, 2, 1, 2, 3, 4, 1, 2, 3, 4, 4, 3
奖励:如果不存在完整模式,请避免附加i(即,允许1,2,3,4但不允许1,2,3)
示例:
find_sublists_in_list([7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5],[1,2,3,4])
[1,2,3,4],[1,2,3,4],[1,2,3,4]
find_sublists_in_list([7,2,1,2,3,2,1,2,3,6,9,9,1,2,3,4,7,4,3,1,2,6],[1,2,3,4])
[1,2,3],[1,2,3],[1,2,3]
列表包含命名元组。
答案 0 :(得分:35)
我知道这个问题是5个月大并且已经“被接受”了,但谷歌搜索一个非常相似的问题带我到这个问题,所有的答案似乎有几个相当重要的问题,加上我很无聊,想要试试我的答案,所以我只是滔滔不绝地说出我发现的东西。
问题的第一部分,据我所知,非常简单:只需返回原始列表,其中所有元素都不会被“模式”过滤掉。按照这个想法,我想到的第一个代码使用了filter()函数:
def subfinder(mylist, pattern):
return list(filter(lambda x: x in pattern, mylist))
我会说这个解决方案肯定比原始解决方案更简洁,但它不是更快,或者至少不是很明显,如果没有很好的理由使用它们,我会尽量避免使用lambda表达式。事实上,我能提出的最佳解决方案是简单的列表理解:
def subfinder(mylist, pattern):
pattern = set(pattern)
return [x for x in mylist if x in pattern]
这个解决方案比原版解决方案更优雅,速度更快:理解速度比原版速度快120%,同时将模式投射到第一个碰撞中,在我的测试中速度提高了320%。
现在获得奖金:我会直接进入它,我的解决方案如下:
def subfinder(mylist, pattern):
matches = []
for i in range(len(mylist)):
if mylist[i] == pattern[0] and mylist[i:i+len(pattern)] == pattern:
matches.append(pattern)
return matches
这是Steven Rumbalski的“低效单线程”的变体,通过添加“mylist [i] == pattern [0]”检查,并且由于python的短路评估,显着快于两者原始语句和itertools版本(以及我所能提供的所有其他解决方案)和它甚至支持重叠模式。你去吧。
答案 1 :(得分:4)
这将获得您问题的“奖励”部分:
pattern = [1, 2, 3, 4]
search_list = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5]
cursor = 0
found = []
for i in search_list:
if i == pattern[cursor]:
cursor += 1
if cursor == len(pattern):
found.append(pattern)
cursor = 0
else:
cursor = 0
对于非奖金:
pattern = [1, 2, 3, 4]
search_list = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5]
cursor = 0
found = []
for i in search_list:
if i != pattern[cursor]:
if cursor > 0:
found.append(pattern[:cursor])
cursor = 0
else:
cursor += 1
最后,这个处理重叠:
def find_matches(pattern_list, search_list):
cursor_list = []
found = []
for element in search_list:
cursors_to_kill = []
for cursor_index in range(len(cursor_list)):
if element == pattern_list[cursor_list[cursor_index]]:
cursor_list[cursor_index] += 1
if cursor_list[cursor_index] == len(pattern_list):
found.append(pattern_list)
cursors_to_kill.append(cursor_index)
else:
cursors_to_kill.append(cursor_index)
cursors_to_kill.reverse()
for cursor_index in cursors_to_kill:
cursor_list.pop(cursor_index)
if element == pattern_list[0]:
cursor_list.append(1)
return found
答案 2 :(得分:1)
list_with_noise = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5]
string_withNoise = "".join(str(i) for i in list_with_noise)
known_pattern = [1,2,3,4]
string_pattern = "".join(str(i) for i in known_pattern)
string_withNoise.count(string_pattern)
答案 3 :(得分:1)
基于迭代器的方法仍然基于朴素算法,但是尝试使用.index()
来进行尽可能多的隐式循环:
def find_pivot(seq, subseq):
n = len(seq)
m = len(subseq)
stop = n - m + 1
if n > 0:
item = subseq[0]
i = 0
try:
while i < stop:
i = seq.index(item, i)
if seq[i:i + m] == subseq:
yield i
i += 1
except ValueError:
return
与其他几种具有不同程度的显式循环的方法相比:
def find_loop(seq, subseq):
n = len(seq)
m = len(subseq)
for i in range(n - m + 1):
if all(seq[i + j] == subseq[j] for j in (range(m))):
yield i
def find_slice(seq, subseq):
n = len(seq)
m = len(subseq)
for i in range(n - m + 1):
if seq[i:i + m] == subseq:
yield i
def find_mix(seq, subseq):
n = len(seq)
m = len(subseq)
for i in range(n - m + 1):
if seq[i] == subseq[0] and seq[i:i + m] == subseq:
yield i
一个会得到:
a = list(range(10))
print(a)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = list(range(5, 10))
print(b)
# [5, 6, 7, 8, 9]
funcs = find_pivot, find_loop, find_slice, find_mix,
for func in funcs:
print()
print(func.__name__)
print(list(func(a * 10, b)))
aa = a * 100
%timeit list(func(aa, b))
random.shuffle(aa)
%timeit list(func(aa, b))
# find_pivot
# [5, 15, 25, 35, 45, 55, 65, 75, 85, 95]
# 10000 loops, best of 3: 49.6 µs per loop
# 10000 loops, best of 3: 50.1 µs per loop
# find_loop
# [5, 15, 25, 35, 45, 55, 65, 75, 85, 95]
# 1000 loops, best of 3: 712 µs per loop
# 1000 loops, best of 3: 680 µs per loop
# find_slice
# [5, 15, 25, 35, 45, 55, 65, 75, 85, 95]
# 10000 loops, best of 3: 162 µs per loop
# 10000 loops, best of 3: 162 µs per loop
# find_mix
# [5, 15, 25, 35, 45, 55, 65, 75, 85, 95]
# 10000 loops, best of 3: 82.2 µs per loop
# 10000 loops, best of 3: 83.9 µs per loop
请注意,这比当前接受测试的答案快30%。
答案 4 :(得分:0)
假设:
a_list = [7,2,1,2,3,4,2,1,2,3,4,9,9,1,2,3,4,7,4,3,1,2,3,5]
pat = [1,2,3,4]
这是一个效率低下的一个班轮:
res = [pat for i in range(len(a_list)) if a_list[i:i+len(pat)] == pat]
这是一个更高效的itertools版本:
from itertools import izip_longest, islice
res = []
i = 0
while True:
try:
i = a_list.index(pat[0], i)
except ValueError:
break
if all(a==b for (a,b) in izip_longest(pat, islice(a_list, i, i+len(pat)))):
res.append(pat)
i += len(pat)
i += 1
答案 5 :(得分:0)
解决问题的惯用,可组合的解决方案。
首先,我们需要借用an itertools
recipe,consume
(它从迭代器中消耗并丢弃给定数量的元素。然后我们采用itertools
pairwise
的方法},并使用nwise
将其扩展为consume
函数:
import itertools
def nwise(iterable, size=2):
its = itertools.tee(iterable, size)
for i, it in enumerate(its):
consume(it, i) # Discards i elements from it
return zip(*its)
现在我们已经有了,解决红利问题非常简单:
def find_sublists_in_list(biglist, searchlist):
searchtup = tuple(searchlist)
return [list(subtup) for subtup in nwise(biglist, len(searchlist)) if subtup == searchtup]
# Or for more obscure but faster one-liner:
return map(list, filter(tuple(searchlist).__eq__, nwise(biglist, len(searchlist))))
同样,对主要问题的解决方案更简洁,更快速(如果不那么漂亮)取代:
def subfinder(mylist, pattern):
pattern = set(pattern)
return [x for x in mylist if x in pattern]
使用:
def subfinder(mylist, pattern):
# Wrap filter call in list() if on Python 3 and you need a list, not a generator
return filter(set(pattern).__contains__, mylist)
此行为方式相同,但避免需要将临时set
存储到名称,并将所有过滤工作推送到C.
答案 6 :(得分:0)
def sublist_in_list(sub,lis): 在str(lis).strip('[]')中返回str(sub).strip('[]')