2017-06-07 99 views
0

我已經使用PHP好幾年了,現在我正在嘗試轉向新的PHP。我對學習python感興趣。什麼是相當於Python的foreach php

在PHP中,我們使用的foreach是這樣的:

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

我們如何在python這個代碼集成?

+9

可能的重複[在Python 3中是否有'foreach'函數?](https://stackoverflow.com/questions/18294534/is-there-a-foreach-function-in-python-3 ) – Qirel

回答

4

Python沒有foreach語句本身。它具有內置於語言中的循環。

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?

2

foreach聲明的等效實際上是蟒蛇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 

然而,因爲他們是一個shallow copy值得一提的是,這種方式使用的for循環,當你不到位編輯迭代的值。

>>> 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] 

相反,你將不得不使用iterable的索引。

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