[英]What python built-in function can apply some function to every element of list in-place?
I have function sqr(n) and list array .我有 function sqr(n)和 list array 。 Is there python built-in function that apply sqr(n) to every element of array in-place (elements change inside the array )?是否有 python 内置 function 将sqr(n)应用于数组的每个元素(数组内部的元素发生变化)? Some tricks with map() function or other built-in functions are also wanted.还需要一些使用map() function 或其他内置函数的技巧。
Of course, this can be done using map() function, but it creates an iterator, and you get a new list (the old list doesn't change):当然,这可以使用map() function 来完成,但它会创建一个迭代器,并且你会得到一个新列表(旧列表不会改变):
def sqr(n):
return n ** 2
array = [1, 2, 3, 4, 5]
array = list(map(sqr, array)) # have to reassign name to new list but elements don't change in old one.
print(array) # output: [1, 4, 9, 16, 25]
I want something like this:我想要这样的东西:
def sqr(n):
return n ** 2
array = [1, 2, 3, 4, 5]
some_built_in_function(sqr, array)
print(array) # output: [1, 4, 9, 16, 25]
There's no built-in function, but you can accomplish the same result using map
and slice assignment.没有内置的 function,但您可以使用map
和切片分配来实现相同的结果。
array[:] = map(sqr, array)
(If you needed an expression rather than a statement, you could use the monstrosity (如果你需要一个表达式而不是一个语句,你可以使用 monstrosity
array.__setitem__(slice(None), map(sqr, array))
which is essentially how the slice assignment is implemented.这基本上就是切片分配的实现方式。 ) )
There's no built-in function, but it's easy to write one yourself:没有内置function,但是自己写一个很容易:
def mapinplace(l, fun):
for i, val in enumerate(l):
l[i] = fun(val)
array = [1, 2, 3, 4, 5]
mapinplace(array, sqr)
Since you are most likely operating on numbers, I'll post the obligatory numpy solution.由于您很可能对数字进行操作,因此我将发布强制性 numpy 解决方案。 Numpy isn't exactly built-in, but it's pretty close: the @
operator in python was made for numpy, for example. Numpy 不是完全内置的,但它非常接近:例如,python 中的@
运算符是为 numpy 制作的。
This solution will only be in-place if the input is a numpy array rather than a list:仅当输入是 numpy 数组而不是列表时,此解决方案才会就地:
np.square(x, out=x)
Most element-wise numpy operations can be done in-place like this.大多数元素方面的 numpy 操作可以像这样就地完成。
You can use list comprehension as follows to achieve this您可以按如下方式使用列表理解来实现此目的
array = [1, 2, 3, 4, 5]
array = [i**2 for i in array]
print(array)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.