简体   繁体   English

Python:如何仅使用while循环返回列表而不修改原始列表?

[英]Python: How to return a list without modifying the original list using a while loop only?

Say I have a function called everythird that takes a list as its parameter and returns a new list containing every third element of the original list, starting from index 0. I know how to do this using slice notation (return everythird[0::3]), but we have to use a while loop only. 假设我有一个名为everything的函数,该函数将一个列表作为其参数,并从索引0开始返回一个包含原始列表的每三个元素的新列表。我知道如何使用切片符号执行此操作(返回everythird [0 :: 3 ]),但我们只能使用while循环。 If I type in everythird([1, 2, 3, 4, 5, 6, 7, 8]), I want it to return [1, 4, 7]. 如果我输入的是三分之一([1、2、3、4、5、6、7、8]),我希望它返回[1、4、7]。 I tried a few different ways, but I'm not getting a list back, or I only get one value back. 我尝试了几种不同的方法,但没有得到列表,或者只有一个值。 How do I return a list? 如何返回列表? Also how do you know for certain whether something modifies or doesn't modify an original list? 另外,您如何确定某些内容是否修改了原始列表?

Thank you. 谢谢。

This is one of the ways I attempted this: every_third([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) 这是我尝试的方法之一:every_third([1、2、3、4、5、6、7、8、9、10、11])

def everythird(l):
    '''(list) -> list
    Returns every third element of original list, starting at index 0'''

    i = 0
    while i < len(l):
        print(l[i])
        i += 3

This prints 此打印

1
4
7

If you need to do this with a while loop, you could do it by appending each element to a list rather than printing it, and then returning that list: 如果需要使用while循环来执行此操作,可以通过将每个元素附加到列表中而不是打印它,然后返回该列表来做到这一点:

def everythird(l):
    i = 0
    ret = []
    while i < len(l):
        ret.append(l[i])
        i += 3
    return ret

Though as you note, it would certainly be preferably to do 尽管您已经注意到,最好还是这样做

def everythird(l):
    return l[0::3]

Or if you were allowed to use a for loop: 或者,如果允许您使用for循环:

def everythird(l):
    ret = []
    for i in range(0, len(l), 3):
        ret.append(l[i])
    return ret

Finally, if you were allowed to use a list comprehension: 最后,如果您被允许使用列表理解:

def everythird(l):
    return [l[i] for i in range(0, len(l), 3)]

The slice indexing is certainly the best, but in any case a while loop might be the worst way to do it. 切片索引当然是最好的,但是无论如何,while循环可能是最糟糕的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM