Python 相当于 php 的 foreach($array as $key => &$value)
有没有与此 PHP 表示法等效的东西,它会更改原始数组(注意引用运算符)?
// increase value of all items by 1
foreach ($array as $k => &$v) {
$v++;
}
我只知道这种方式,不太优雅:
for i in range(len(array)):
array[i] += 1
is there any equivalent to this PHP notation, which changes the original array (be aware of reference operator)?
// increase value of all items by 1
foreach ($array as $k => &$v) {
$v++;
}
I know only this way, which is not so elegant:
for i in range(len(array)):
array[i] += 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当调用内置的
enumerate()
函数时在列表上,它返回一个可以迭代的对象,返回一个计数和从列表返回的值。When the built in
enumerate()
function is called on a list, it returns an object that can be iterated over, returning a count and the value returned from the list.您可以使用列表理解:
You could use list comprehension:
关于参考文献。
在Python中,每个值都是对象,每个“变量”都是对该对象的引用。赋值从不复制值,它总是分配引用。
因此,默认情况下,v in
for k,v in enumerate([1,2,3])
也是引用。然而,大多数基本“类型”的对象都是不可变的,因此当您执行immutable_object_reference += 1
时,您将创建int
的新实例并将immutable_object_reference
更改为指向新实例。当我们的值是可变类型时,引用的工作方式与 PHP 中相同:
Regarding references.
In python, every value is object, and every 'variable' is reference to the object. Assignment never copies value, it always assigns reference.
So v in
for k,v in enumerate([1,2,3])
is reference too, by default. However most objects of basic 'types' are immutable, therefore when you doimmutable_object_reference += 1
you create new instance ofint
and changeimmutable_object_reference
to point to new instance.When our values are of mutable types, references work same as in PHP:
我不知道能够获取指向列表项的指针,但是 http://effbot.org/zone/python-list.htm:
I'm unaware of being able to get a pointer to a list item, but a cleaner way to access by index is demonstrated by http://effbot.org/zone/python-list.htm: