将C函数转换为Python函数

将C函数转换为Python函数,python,arrays,function,python-3.x,Python,Arrays,Function,Python 3.x,此函数用于搜索数组中元素的编号,如果存在,则返回数组中元素的编号;如果数组中不存在输入编号,则返回-1 int iSearch (int st[],int len,int no) { int i; for (i=1;i<=len;i++) //len=lenth of the array , no = the number that we want to search in the array , st[] = the array if (st[i]==no)

此函数用于搜索数组中元素的编号,如果存在,则返回数组中元素的编号;如果数组中不存在输入编号,则返回-1

int iSearch (int st[],int len,int no)
{
    int i;
    for (i=1;i<=len;i++) //len=lenth of the array , no = the number that we want to search in the array , st[] = the array
      if (st[i]==no)
          return i;
      return -1;
}

以下是等效的循环:

def iSearch(lst,no):
  for i,x in enumerate(lst):
    if x == no:
      return i
  return -1
但是,有一个函数lst.indexno正在执行您需要的操作,但它的效率更高:

def iSearch(lst,no):
  if no in lst:
    return lst.index(no)
  return -1
或者使用try/except可能是最快的:

def iSearch(lst,no):
  try:
    return lst.index(no)
  except ValueError:
    return -1

如果你把下次遇到的错误包括进去,那会有帮助的

您的代码有一些问题:1。列表是已存在的对象2的名称。您只需要检查第一项是否是所需的对象,因为此时,两个分支都返回。3.访问列表元素需要方括号,而不是括号

这似乎有效:

def linear_search_c(l,length,num):                                                                                                                    
  for x in range(0,length):                                                   
    if (l[x] == num):                                                       
        return x                                                            
  return -1

另外,如果数组已排序,则有比线性搜索更好的列表搜索方法:

您不需要有长度!使用Python的哪种版本?如果使用正确的类型,则使用Python 3.6List.GETNO,-1:列表是DIST。甚至不要考虑将C代码1:1移植到Python。如果你想把代码移植到一种语言中,你必须先学习它。我在你的密码里是什么?@DYZ:我已经同意你是对的。这仍然有XY问题的坏味道,因此我提供了另一种观点。事实上,我很有信心OP需要一些与他所做的非常不同的东西BTW@Jean-弗朗索瓦·法布说得对。明白了:我已经投了更高的票,你也不必为你可能对我糟糕的答案投了反对票而感到难过。我不认为这是针对个人的,不像那些傻瓜,当你重复一个问题时,他们会投你一票。这里不需要x=0。对于排序数组,您可以使用对分python模块。谢谢Fabre,很高兴了解对分。
def linear_search_c(l,length,num):                                                                                                                    
  for x in range(0,length):                                                   
    if (l[x] == num):                                                       
        return x                                                            
  return -1