pythonにおいての for each 文

 



pythonにおいての for each 文はどのように記述するのでしょうか?





Pythonでは、`for each`文に相当する構文は、

単に`for`文を使用して記述します。


Pythonの`for`文は、リストやタプル、辞書、文字列、セット、

あるいはジェネレータなどのイテラブルオブジェクトを直接繰り返す構文を提供します。



以下は例を挙げます:



### リストの各要素を繰り返す

```python


fruits = ["apple", "banana", "cherry"]


for fruit in fruits:

    print(fruit)

```


**出力:**


```


apple

banana

cherry


```


### 辞書のキーと値を繰り返す


```python


person = {"name": "Alice", "age": 25, "city": "New York"}

for key, value in person.items():

    print(f"{key}: {value}")

```



**出力:**


```


name: Alice

age: 25

city: New York


```


### インデックス付きの繰り返し


`enumerate()`を使用すると、要素とそのインデックスを同時に取得できます。


```python


fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):

    print(f"{index}: {fruit}")

```


**出力:**


```


0: apple

1: banana

2: cherry


```


### 集合の繰り返し

```python


colors = {"red", "blue", "green"}

for color in colors:

    print(color)

```


### 文字列の繰り返し


```python


word = "hello"

for letter in word:

    print(letter)

```


### 範囲を繰り返す


`range()`を使用して、特定の範囲の数値を繰り返します。


```python


for number in range(5):  # 0から4まで

    print(number)

```


Pythonの`for`文は非常に柔軟で、

イテラブルオブジェクトを直接操作できるため、シンプルかつ強力です。


コメント