您如何按顺序在另一个列表中找到一个列表中的元素?
How do you find the elements in one list, in that order, in another list?
我正在尝试将一个列表 (list1) 中的所有项目与另一个列表 (list2) 中的某些项目进行匹配。
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
对于 list1 中的每个连续对象,我想找到该模式出现在 list2 中的所有索引:
基本上,我希望结果是这样的:
“r 在 list2 中的索引 0,2 处”
“r,g 在索引处,list2 中的 1,3”(我只想找到模式中的最后一个索引)
"r,g,g 在列表 2 中的索引 4"
至于我尝试过的事情:
嗯……很多。
最接近的是这个:
print([x for x in list1 if x not in set(list2)])
这对我不起作用,因为它不寻找一组对象,它只测试一个对象在 list1 中在 list2 中。
我真的不需要 pythonic 甚至那么快的答案。只要能用!
非常感谢任何帮助!
谢谢!
尝试一下:
list1 = ['r','g','g']
list2 = ['r','g','r','g','g']
def inits(lst):
for i in range(1, len(lst) + 1):
yield lst[:i]
def rolling_windows(lst, length):
for i in range(len(lst) - length + 1):
yield lst[i:i+length]
for sublen, sublst in enumerate(inits(list1), start=1):
inds = [ind for ind, roll
in enumerate(rolling_windows(list2, sublen), start=sublen)
if roll == sublst]
print(f"{sublst} is in list2 at indices: {inds}")
# ['r'] is in list2 at indices: [1, 3]
# ['r', 'g'] is in list2 at indices: [2, 4]
# ['r', 'g', 'g'] is in list2 at indices: [5]
基本上,它使用两个函数(inits
和 rolling_windows
)生成相关的子列表,然后比较它们。
纯 python 解决方案,对于大列表来说会很慢:
def ind_of_sub_list_in_list(sub: list, main: list) -> list[int]:
indices: list[int] = []
for index_main in range(len(main) - len(sub) + 1):
for index_sub in range(len(sub)):
if main[index_main + index_sub] != sub[index_sub]:
break
else: # `sub` fits completely in `main`
indices.append(index_main)
return indices
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
print(ind_of_sub_list_in_list(sub=list1, main=list2)) # [0, 3]
带有两个 for 循环的简单实现,逐个检查两个列表中的条目。
将需要匹配的列表转换为字符串,然后使用正则表达式查找所有子字符串
import re
S1 = "".join(list2) #it will convert your list2 to string
sub_str = ""
for letter in list1:
sub_str+=letter
r=re.finditer(sub_str, S1)
for i in r:
print(sub_str , " found at ", i.start() + 1)
这将为您提供匹配项的起始索引
这是一个很有趣的问题。 Python 具有强大的 列表索引 方法,可让您高效地进行这些比较。从 programming/maths 的角度来看,您要做的是将较长列表的 子列表 与您选择的模式进行比较。这可以通过以下方式实现:
# sample lists
pattern = [1,2,3]
mylist = [1,2,3,4,1,2,3,4,1,2,6,7,1,2,3]
# we want to check all elements of mylist
# we can stop len(pattern) elements before the end
for i in range(len(mylist)-len(pattern)):
# we generate a sublist of mylist, and we compare with list pattern
if mylist[i:i+len(pattern)]==pattern:
# we print the matches
print(i)
此代码将打印 0 和 4,即 mylist 中 [1,2,3] 所在的索引。
如果两个列表中的所有条目实际上都是字符串,则解决方案可以简化为:
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
main = "".join(list2)
sub = "".join(list1)
indices = [index for index in range(len(main)) if main.startswith(sub, index)]
print(indices) # [0, 3]
我们join
都把list都转成一个字符串,然后用startswith
的方法来确定所有的索引。
我正在尝试将一个列表 (list1) 中的所有项目与另一个列表 (list2) 中的某些项目进行匹配。
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
对于 list1 中的每个连续对象,我想找到该模式出现在 list2 中的所有索引:
基本上,我希望结果是这样的:
“r 在 list2 中的索引 0,2 处” “r,g 在索引处,list2 中的 1,3”(我只想找到模式中的最后一个索引) "r,g,g 在列表 2 中的索引 4"
至于我尝试过的事情: 嗯……很多。
最接近的是这个:
print([x for x in list1 if x not in set(list2)])
这对我不起作用,因为它不寻找一组对象,它只测试一个对象在 list1 中在 list2 中。
我真的不需要 pythonic 甚至那么快的答案。只要能用!
非常感谢任何帮助! 谢谢!
尝试一下:
list1 = ['r','g','g']
list2 = ['r','g','r','g','g']
def inits(lst):
for i in range(1, len(lst) + 1):
yield lst[:i]
def rolling_windows(lst, length):
for i in range(len(lst) - length + 1):
yield lst[i:i+length]
for sublen, sublst in enumerate(inits(list1), start=1):
inds = [ind for ind, roll
in enumerate(rolling_windows(list2, sublen), start=sublen)
if roll == sublst]
print(f"{sublst} is in list2 at indices: {inds}")
# ['r'] is in list2 at indices: [1, 3]
# ['r', 'g'] is in list2 at indices: [2, 4]
# ['r', 'g', 'g'] is in list2 at indices: [5]
基本上,它使用两个函数(inits
和 rolling_windows
)生成相关的子列表,然后比较它们。
纯 python 解决方案,对于大列表来说会很慢:
def ind_of_sub_list_in_list(sub: list, main: list) -> list[int]:
indices: list[int] = []
for index_main in range(len(main) - len(sub) + 1):
for index_sub in range(len(sub)):
if main[index_main + index_sub] != sub[index_sub]:
break
else: # `sub` fits completely in `main`
indices.append(index_main)
return indices
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
print(ind_of_sub_list_in_list(sub=list1, main=list2)) # [0, 3]
带有两个 for 循环的简单实现,逐个检查两个列表中的条目。
将需要匹配的列表转换为字符串,然后使用正则表达式查找所有子字符串
import re
S1 = "".join(list2) #it will convert your list2 to string
sub_str = ""
for letter in list1:
sub_str+=letter
r=re.finditer(sub_str, S1)
for i in r:
print(sub_str , " found at ", i.start() + 1)
这将为您提供匹配项的起始索引
这是一个很有趣的问题。 Python 具有强大的 列表索引 方法,可让您高效地进行这些比较。从 programming/maths 的角度来看,您要做的是将较长列表的 子列表 与您选择的模式进行比较。这可以通过以下方式实现:
# sample lists
pattern = [1,2,3]
mylist = [1,2,3,4,1,2,3,4,1,2,6,7,1,2,3]
# we want to check all elements of mylist
# we can stop len(pattern) elements before the end
for i in range(len(mylist)-len(pattern)):
# we generate a sublist of mylist, and we compare with list pattern
if mylist[i:i+len(pattern)]==pattern:
# we print the matches
print(i)
此代码将打印 0 和 4,即 mylist 中 [1,2,3] 所在的索引。
如果两个列表中的所有条目实际上都是字符串,则解决方案可以简化为:
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
main = "".join(list2)
sub = "".join(list1)
indices = [index for index in range(len(main)) if main.startswith(sub, index)]
print(indices) # [0, 3]
我们join
都把list都转成一个字符串,然后用startswith
的方法来确定所有的索引。