[英]Searching through a list with given elements
I am trying to create a function that accepts two lists of integers, where the second list is a subset of the first list, and then returns a list of zeroes and ones, such that K[i] = 1 if L[i] is found within the list M.我正在尝试创建一个 function 接受两个整数列表,其中第二个列表是第一个列表的子集,然后返回零和一的列表,如果 L[i] 为 K[i] = 1在列表 M 中找到。
Here is the code I have created so far:这是我到目前为止创建的代码:
def doSomething(L,M):
K=[]
x=0
for i in range(len(L)):
if L[i]==M[x]:
K.append(1)
x=x+1
else:
K.append(0)
return K
L=[2,17,12,5,66,20,7]
M=[2,12,66]
print(doSomething(L,M))
The output I am expecting is [1, 0, 1, 0, 1, 0, 0] However I get an error in the 5th line of code: "IndexError: list index out of range"我期待的 output 是 [1, 0, 1, 0, 1, 0, 0] 但是我在第 5 行代码中遇到错误:“IndexError: list index out of range”
Any help would be much appreciated.任何帮助将非常感激。
This should work:这应该有效:
K = [1 if x in M else 0 for x in L]
Or as a function:或作为 function:
def doSomething(L, M):
return [1 if x in M else 0 for x in L]
The error in line 5 was due to the fact that length of list M is less than that of L.第 5 行的错误是由于列表 M 的长度小于 L 的长度。
If you are still not comfortable using list comprehension as suggested by Ilia, you may use following code (updated doSomething):如果您仍然不习惯按照 Ilia 的建议使用列表推导,您可以使用以下代码(更新后的 doSomething):
def doSomething(L,M):
K=[]
for i in range(len(L)):
if L[i] in M:
K.append(1)
else:
K.append(0)
return K
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.