2024 桐庐半程马拉松
00:00:00
时间
0.00
距离(公里)
--:--
配速
--
步频
--
心率 (bpm)
--
配速
步频
|
share-image
ESC

Python 列表生成

生成器

列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。

L = []

for x in range(1,11):
L.append(x * x)

print(L)


得出

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是我们可以更简化些

T = [x*x for x in range(1,11)]

print(T)

同样的效果

此外还可以进行判断

    L = [x*x for x in range(1,11) if x%2 ==0]

print(L)

```

输出结果

```python

[4, 16, 36, 64, 100]

例如还可以使用两层循环,可以生成全排列:

    L = [m + n for m in 'ABC' for n in 'XYZ']

print(L)
```


得到

```python

['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

迭代器

判断对象是否可用被迭代


from collections import Iterable

print(isinstance('abc',Iterable)) // 返回布尔型
```

输出下标

```python

for i,value in enumerate(['A','B','C']):

print(i,value)

得到

0 A
1 B
2 C

文章作者:阿文
文章链接: https://www.awen.me/post/22294.html
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 阿文的博客
本文于 2018-04-14 发布,已超过半年(2847天),请注意甄别内容是否已过期。