简体   繁体   English

我在哪里枚举错了?

[英]Where am I going wrong with enumerate?

I know the answer is probably super simple, but I'm absolutely stuck on this short piece of code.我知道答案可能非常简单,但我完全被这段简短的代码所困扰。 The function has no effect on the input list when I run it. function 在我运行时对输入列表没有影响。

def squareEven(array):
    for idx, val in enumerate(array):

        if idx % 2 == 0:
            val = val * val
        else:
            val = val

    return array

array = [1, 2, 4, 9, 20]

print(squareEven(array))

the reason is that the enumerate function does not actually change the array itself but just returns the new one for you to use in the loop.原因是enumerate function 实际上并没有更改array本身,而只是返回新的数组供您在循环中使用。 The simple solution is to save the enumerate(array) into another variable and return it at the end of your function.简单的解决方案是将enumerate(array)保存到另一个变量中,并在 function 的末尾返回它。 Keep in mind, you will get an enumerated array at the end.请记住,最后你会得到一个枚举数组。 You could map it to convert to a form you initially passed.您可以 map 将其转换为您最初通过的表格。

Here are two ways, one bad, one good:这里有两种方法,一种不好,一种很好:

def squareEven(array):
    for idx in range(len(array)):
        if idx % 2 == 0:
            array[idx] = array[idx] * array[idx]
    return array

array = [1, 2, 4, 9, 20]
print(squareEven(array))

This is better, because it doesn't damage the original array as a side effect:这更好,因为它不会损坏原始数组作为副作用:

def squareEven(array):
    new = []
    for idx,val in enumerate(array):
        if idx % 2 == 0:
            new.append(val * val)
        else:
            new.append(val)
    return new

array = [1, 2, 4, 9, 20]

print(squareEven(array))

You can also use the list comprehension to construct a new list with squared values when the index is even.当索引为偶数时,您还可以使用列表推导构造一个具有平方值的新列表。


def squareEven(array):
    return [v**2 if i % 2 == 0 else v for (i, v) in enumerate(array)]

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

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

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