Python循环迭代问题

时间:2017-01-08 05:29:29

标签: python loops iteration

两个版本,返回相反的答案,但总是出错。我不确定我哪里出错了。我已经尝试了一系列其他选项,但这似乎是最接近的。 编辑:需要处于循环中

目标:识别列表中的元素,识别元素何时不在列表中,识别列表何时为[],相应地返回字符串。

if(bool){
    var err = false;
    var handleError = function(e){
    if(err){
      err = true;
      var eDoc = {};
      eDoc.errorCode = 1;
      eDoc.error = e;
      console.log(eDoc);
    }
  }
  var userID = req.body.userID || handleError("no userID");
  console.log(req.body.userID);
  if(userID != null){
    if(!err){
      tokens.db = req.db;
      tokens.session.create(3, userID, function(token){
        res.send('1');
      });
    }else{
      console.log('Token err = true');
    }
  }else{
    console.log('Creator token = null');
    res.send('0');
  }
}else{
    res.send('0');
}

其他测试:

def search_for_string(a_list, search_term):
    i=0
    for search_term in a_list:
        i += 1
        if a_list[i] == search_term: 
            return 'string found!' 
        elif a_list[i] != search_term:
            return 'string not found2'
    if len(a_list) == 0:
        return 'string not found'

apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)


def search_for_string(a_list, search_term):
    i=0
    for search_term in a_list:
        if a_list[i] == search_term: 
            return 'string found!' 
        elif a_list[i] != search_term:
            return 'string not found2'
        i += 1
    if len(a_list) == 0:
        return 'string not found'

apple = search_for_string(['a', 'b', 'c'], 'd')
print(apple)

8 个答案:

答案 0 :(得分:9)

Python让你的生活变得非常容易:

def search_for_string(a_list, search_term):
    if search_term in a_list:
        return 'string found!'
    return 'string not found'

答案 1 :(得分:3)

您的代码中存在一些错误和非Pythonic错误:

def search_for_string2(a_list, search_term):
    i=0  # <----- Not Pythonic! If you want to get index we use enumerate(a_list)
    for search_term in a_list: # <--- search_term passed to function is lost and gets overwritten by elements in a_list.
        i += 1 # <--- Not Pythonic in this context
        if a_list[i] == search_term: #<--- a_list[index+1] == a_list[index]. True if consecutive elements are same else False!
            return 'string found!' #<--- No WRONG!, You didn't find the string, Consecutive elements are same!
        elif a_list[i] != search_term:
            return 'string not found2' #<-- Consecutive elements are not same!
    if len(a_list) == 0:
        return 'string not found'

根据您定义的目标,您可以像这样实现它:

def search_for_string(alist, search_term):
    if not alist:
        return "List is empty"
    if search_term in alist:
        return "First occurence of string Found at index position: " + str(alist.index(search_term))
    else:
        return "String not found"


print(search_for_string(['a', 'b', 'c'], 'd'))
print(search_for_string(['a', 'b', 'c'], 'b'))
print(search_for_string([], 'b'))

输出:

String not found
First occurence of string Found at index position: 1
List is empty

答案 2 :(得分:2)

简短的回答是,!=的返回不符合您的想法,而且列表是0索引而不是1索引。代码实际上比你想象的要简单得多:

def search_for_string(haystack, needle):
    if not haystack: # check for empty list
        return 'List was empty!'
    for x in haystack:
        if needle == x:
            return 'String found!'
    return 'String not found!'

基本上,如果您已经完成并且至少检查过一次每个元素,您只知道是否找不到字符串。但是,当你找到它时,你知道是否找到了一个字符串。

现在解释代码的问题:

  1. 此版本不起作用,因为(1)它跳过列表中的第一个元素,(2)只有在检查第一个元素后才返回找不到的字符串:

    def search_for_string(a_list, search_term):
        i=0
        for search_term in a_list:
            i += 1
            if a_list[i] == search_term: # whoops this comparison checks for succeeding elements!
                return 'string found!' 
            elif a_list[i] != search_term: # whoops this part returns  even before all succeeding elements are checked.
                return 'string not found2'
        if len(a_list) == 0:
            return 'string not found'
    
    apple = search_for_string(['a', 'b', 'c'], 'd')
    # In the list ['a', 'b', 'c']
    # element [0] = 'a'
    # element [1] = 'b'
    # element [2] = 'c'
    print(apple)
    
  2. 为了进一步解释,让我们逐步完成您的代码:

    # search_term == 'd'
    # a_list = [ 'a', 'b', 'c' ]
    i = 0 # at this point i == 0
    for search_term in a_list:  
        # Oh no!  we lost the search term that we passed into the 
        # function because we are using it as the loop iterator
        # search_term == 'a'
        i += 1 # i == 1
        if a_list[i] == search_term: 
            # checks to see if 'b' == 'a'
            return 'string found!'
        elif a_list[i] != search_term:
            # checks to see if 'b' != 'a'
            return 'string not found!' 
            # and we return after one iteration of the loop.
    

    您的第二个版本存在同样的问题(1)(2),但避免了未检查第一个元素的问题。

答案 3 :(得分:1)

search_for_string函数中存在许多错误。

主要问题是您要覆盖变量search_term的值。还有其他问题导致输出错误。

这是一个更简单的功能版本,它符合您的所有要求。

def search_for_string(a_list, search_item):
  if(len(a_list) == 0):
       return 'List is empty'
  else:
    for search_term in a_list:
        if search_term == search_item: 
            return 'string found!' 
    return 'string not found'

答案 4 :(得分:1)

您的代码中有很多错误。有些很重要,有些则不重要。我会尝试解决这些问题:

  • 您正在接收变量search_term作为函数参数,但是您可以在for循环中使用它来覆盖它的值。
  • 您按值迭代a_list,但随后尝试使用循环变量i按索引进行迭代。不要这样做。您已经按价值进行迭代,您不需要同时执行这两项操作。
  • 您正在尝试测试功能的 end a_list是否为空。在开始时做。更好的是,抛弃if语句,只需在函数结束时返回。如果a_list为空,则不会运行for循环。

现在,我在这里重写你的功能:

>>> def search_for_string(lst, key):
    # only iterate by value.
        for string in lst:
            # we only need to test once
            # if `key` is equal to the
            # current string we are on.
            if string == key:
                return 'string found'
        # no need to test if the list
        # is empty. The for loop will
        # never be run if it is, and
        # this return statement will
        # execute.
        return 'string not found'

>>> search_for_string(['a', 'b', 'c'], 'd')
'string not found'
>>> search_for_string(['a', 'b', 'c'], 'b')
'string found'
>>> search_for_string([], 'b')
'string not found'
>>> 

答案 5 :(得分:1)

对于您的代码,您应该注意到您没有正确搜索。您传入search_term,但for x in y中的变量将x设置为等于y中下一项的值。所以,如果你有for x in [1, 2, 3],它第一次运行就会设置x = 1,等等。所以第一个函数会检查'a'=='b',它不是,第二个函数会检查是否'a'=='a',它是 - 但你不是在找什么!

查找项目是否在列表中的最佳方法是

x in list

如果x在列表中,则返回True或False! (不要使用变量'list',这是不好的做法,因为它会影响内置函数)。

这样做的更多Pythonic方法就是

def search_for_string(a_list, search_term):
    if search_term in a_list:
        return 'string found!'
    elif not a_list:  # realistically you'd put this before here but I'm trying to mirror your code--why might you put this earlier? Because it's less costly than searching a list.
        return 'empty list!'
    else:
        return 'string not found!'

另请注意bool([])返回False,这是我们检查列表是否为空的方式。

按照你的方式去做,我们不需要使用索引值,但你必须做很多额外的,不必要的工作。

def search_for_string(a_list, search_term):
    for index, item in enumerate(a_list):
        if a_list[index] == search_term:
            return 'string found!'
            # what do you think the value of 'item' is here? it's equal to a_list[index]!
        elif len(a_list) == 0:  # again, you'd put this earlier--why make your computer do the work? it doesn't have to. Also, you could just do elif not a_list
            return 'string not found'
        else: 
            continue
    return 'string not found2'

答案 6 :(得分:1)

以前的答案涵盖了与您的代码相关的大多数问题,而@Stephen Rauch给出的答案总结了解决问题的最Pythonic方法。

还有一件事使你的代码不能做你喜欢的事情,即使所有其他的东西都是正确的。

当您在函数中return时,您实际上正在退出该函数。

所以,实际上,使用您一直在尝试的for循环方法,您只需检查a_list中的第一个值,然后返回&#39;找到&#39;如果它符合您的搜索条件,并返回“未找到”&#39;如果第一个值符合您的搜索条件,然后退出您的函数。

基本上,你永远不会超过第一个值。

答案 7 :(得分:1)

首先, 第一种方法和第二种方法的差异是在执行if语句之前和之后递增i。如果先递增i,则循环将找不到列表第一个元素的值。 你使用i作为增量,但在python中没有必要。您可以通过使用元素是否在列表中来找出。

def search_for_string(a_list, search_term):

    #if a_list is empty, return False
    if len(a_list) == 0:
          return False
    #if search_term has an element in a_list return the string
    if search_term in a_list:
          return "string found"

    return "string not found"