python中foreach php的等价物是什么

pwuypxnk  于 2023-02-03  发布在  PHP
关注(0)|答案(4)|浏览(140)

我已经使用PHP好几年了,现在,我正试图转向一个新的。我对学习Python很感兴趣。
在PHP中,我们使用foreach的方式如下:

<?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value; 
}

我们如何将这些代码集成到python中呢?

toiithl6

toiithl61#

Python本身没有foreach语句,它有内置的for循环。

for element in iterable:
    operate(element)

如果您真的愿意,可以定义自己的foreach函数:

def foreach(function, iterable):
    for element in iterable:
        function(element)

参考:Is there a 'foreach' function in Python 3?

rqenqsqc

rqenqsqc2#

foreach语句的等价物实际上是python for语句。
例如:

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     print(i)
...
1
2
3
4
5

它实际上适用于python中的所有iterables,包括字符串。

>>> word = "stackoverflow"
>>> for c in word:
...     print(c)
...
s
t
a
c
k
o
v
e
r
f
l
o
w

然而,值得注意的是,当以这种方式使用for循环时,您并没有在适当的位置编辑可迭代对象的值,因为它们是shallow copy

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     i += 1
...     print(i)
... 
2
3
4
5
6
>>> print(items)
[1, 2, 3, 4, 5]

相反,您必须使用可迭代对象的索引。

>>> items = [1, 2, 3, 4, 5]
>>> for i in range(len(items)):
...     items[i] += 1
... 
>>> print(items)
[2, 3, 4, 5, 6]
gr8qqesn

gr8qqesn3#

请参见此处的文档:https://wiki.python.org/moin/ForLoop

collection = ['John', 'Adam', 'Ken']
for x in collection:
    print collection[x]
gojuced7

gojuced74#

如果您需要获取索引,可以尝试以下操作:

var = ('John', 'Adam' , 'Ken')
for index in range(len(var)):
    item = var[index]
    print(item)

相关问题