很难理解这个while循环

2024-04-16 15:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个函数,它接受一个列表的输入和一个0或1的选项。如果它是0,我想返回一个大于绝对值5的元素列表。如果是选项1,我想返回奇数元素列表。我也想用while循环。我哪里做错了??你知道吗

def splitList2(myList, option):
    nList = []
    element = 0 
    while element < len(myList):
        if option == 0:
            if abs(element) > 5:
                nList.append(element)
        elif option == 1:
            if element % 2:
                nList.append(element)
        element = element + 1
    return nList

Tags: 函数元素列表lenifdef选项element
3条回答

我只回答“我哪里做错了?”问题。你知道吗

  1. 你有两个不同的问题。这些函数属于两个不同的函数,您将彼此独立地调试它们。你知道吗
  2. 您已经选择使用“while循环”作为解决方案的一部分。这可能是解决方案的一部分,但可能是一种不好的方法。也许这对你的任何一个或两个问题都没有好处。你知道吗
  3. 您对python还是个新手,可能还不熟悉一般的编程。没什么不对的。祝你好运。在尝试任何解决方案之前,你应该学会把问题简化成最简单的形式。通常对于你遇到的任何问题,你都可以找到一些容易解决的小问题。一个接一个地解决它们,然后将小问题的解决方案集成到原始问题的解决方案中。你知道吗
  4. 在这两个问题中,您可能会发现在python中,首选“for element In iterable:”。例如,“for words in words:”、“for item in alist”等

您使用element作为元素索引的名称,这很混乱。实际上,稍后将检查/追加索引,而不是myList中相应的元素!你知道吗

替代版本:

def splitList2(myList, option):
    nList = []
    n = 0 
    while n < len(myList):
    element = myList[n]
        if option == 0:
            if abs(element) > 5:
                nList.append(element)
        elif option == 1:
            if element % 2:
                nList.append(element)
        element = element + 1
    return nList

而且while也不是执行此类任务的最佳选择。我假设您是出于教育的原因,尝试使用while来实现这一点。然而,一种更为python的方式是:

def splitList2(myList, option):

    options = {
        0: lambda n: abs(n) > 5,
        1: lambda n: n % 2
    }

    return filter(options[option], nList)

element是索引,而不是来自myList的元素。我会将当前的element变量重命名为index,然后在while循环的顶部添加element = myList[index]

def splitList2(myList, option):
    nList = []
    index = 0 
    while index < len(myList):
        element = myList[index]
        if option == 0:
            if abs(element) > 5:
                nList.append(element)
        elif option == 1:
            if element % 2:
                nList.append(element)
        index = index + 1
    return nList

当然,在这里使用for element in myList循环而不是while循环会更简单。你知道吗

相关问题 更多 >