﻿ 我们为什么要减少Python中循环的使用 - 军军小站|张军博客

# 我们为什么要减少Python中循环的使用

Python 提供给我们多种编码方式。

```
x = [1,3,5,7,9]
sum_squared = 0

for i in range(len(x)):
sum_squared+=x[i]**2
```

```
x = [1,3,5,7,9]
sum_squared = 0

for y in x:
sum_squared+=y**2
```

```
x = [1,3,5,7,9]
sum_squared = sum([y**2 for y in x])
```

```
x = [1,2,3,4,5,6,7,8,9]
even_squared = [y**2 for y in x if y%2==0]
# 输出结果：
[4,16,36,64]
```

if-else？

```
x = [1,2,3,4,5,6,7,8,9]
squared_cubed = [y**2 if y%2==0 else y**3 for y in x]
# 输出结果：
[1, 4, 27, 16, 125, 36, 343, 64, 729]
```

• 可以不用 for 做到吗？更 Pythonic 的风格。
• 可以用 List Comprehension 做到吗？如果是，使用它。
• 可以不索引数组吗？如果不是，考虑使用 enumerate。

```
L = ['blue', 'yellow', 'orange']
for i, val in enumerate(L):
print("index is %d and value is %s" % (i, val))
# 输出结果：
index is 0 and value is blue
index is 1 and value is yellow
index is 2 and value is orange
```

```
x = [1,2,3,4,5,6,7,8,9]
{k:k**2 for k in x}
# 输出结果：
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
```

```
x = [1,2,3,4,5,6,7,8,9]
{k:k**2 for k in x if x%2==0}
# 输出结果：
{2: 4, 4: 16, 6: 36, 8: 64}
```

```
x = [1,2,3,4,5,6,7,8,9]
{k:k**2 if k%2==0 else k**3 for k in x}
# 输出结果：
{1: 1, 2: 4, 3: 27, 4: 16, 5: 125, 6: 36, 7: 343, 8: 64, 9: 729}
```

QQ号联系： 360901061

【本文对您有帮助就好】