Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较列表的子集并返回它在列表中的位置_Python_List_Intersection - Fatal编程技术网

Python 比较列表的子集并返回它在列表中的位置

Python 比较列表的子集并返回它在列表中的位置,python,list,intersection,Python,List,Intersection,我有两个列表a和b,b是a中某个地方的一个小子集 b = ['apple','banana','carrot'] a = list of length 100 which somewhere contains b at indices 12,13,14. 我想在a中搜索b并返回索引12,13,14 我目前的想法是做两个嵌套循环来寻找模式,但我希望有一个更干净/更简单的解决方案 这里有一个简单的可能性: b = ['a', 'b', 'c'] a = ['t', 'z', 'd', 'a', '

我有两个列表a和b,b是a中某个地方的一个小子集

b = ['apple','banana','carrot']
a = list of length 100 which somewhere contains b at indices 12,13,14.
我想在a中搜索b并返回索引12,13,14


我目前的想法是做两个嵌套循环来寻找模式,但我希望有一个更干净/更简单的解决方案

这里有一个简单的可能性:

b = ['a', 'b', 'c']
a = ['t', 'z', 'd', 'a', 'b', 'c', 't', 's', 'a', 'b']

[i for i in range(len(a)) if a[i:i+len(b)] == b]
输出:
[3]


返回列表
a
中列表
b
的第一个元素的索引。请注意,如果
b
a
中重复了不止一次,此方法将返回
b
a
中重复的两个索引。这里有一个简单的可能性:

b = ['a', 'b', 'c']
a = ['t', 'z', 'd', 'a', 'b', 'c', 't', 's', 'a', 'b']

[i for i in range(len(a)) if a[i:i+len(b)] == b]
  >>> a=[[1,2,3],[4,5,6],[7,8,9]];
   >>> b=[4,5,6];
   >>> if b in a:
    print"found at:",a.index(b);
enter code here

found at: 1
输出:
[3]

返回列表
a
中列表
b
的第一个元素的索引。请注意,如果
b
a
中重复多次,此方法将返回
b
a
中重复的两个索引

  >>> a=[[1,2,3],[4,5,6],[7,8,9]];
   >>> b=[4,5,6];
   >>> if b in a:
    print"found at:",a.index(b);
enter code here

found at: 1
//来自pythonshell


//从pythonshell

yes,基本方法是两个嵌套循环。对于你的问题,它工作得很好。您还可以将列表视为字符串,并使用其中任何一个(KMP通常非常流行)(其中一些算法可能需要输入实际上是字符串,因此将不适用)是的,基本方法是2个嵌套循环。对于你的问题,它工作得很好。您还可以将列表视为字符串,并使用其中的任何一个(KMP通常非常流行)(其中一些算法可能需要输入实际上是字符串,因此不适用)@ NFNNEIL<代码> 12, 13, 14 <代码>,在这些情况下,这些都是正确的索引。使用这种方法可以得到
3
,从中可以扣除索引
3、4、5
@nfnneil
12、13、14
,如果这些是正确的索引。使用这种方法,您可以得到
3
,从中您可以扣除索引将是
3、4、5
。这不是一个答案,因为OP有一个平面列表,而不是一个已经被方便地切分的列表。这不是一个答案,因为OP有一个平面列表,而不是一个已经被方便地切分的列表。