[ 返回值 for 元素 in 可迭代对象 if 条件 ]
[]
,内部是 for
循环,if
条件语句可选[expr for item in iterable if cond1 if cond2 if cond3 ...]
上面代码等价于下面代码:
# 适合于 一斜到底 单分支 if 语句
ret = []
for item in iterable:
if cond1:
if cond2:
if cond3:
ret.append(expr)
[expr for i in iterable1 for j in iterable2]
上面代码等价于下面代码:
ret = []
for i in iterable1:
for j in iterable2:
ret.append(expr)
# 方法一
even = []
for i in range(10):
if i % 2 == 0:
even.append(i)
print(even)
[0, 2, 4, 6, 8]
# 方法二
even = [x for x in range(10) if x % 2 == 0]
print(even)
[0, 2, 4, 6, 8]
# Jupyter Notebook 环境
%%timeit
even = []
for i in range(100):
if i % 2 == 0:
even.append(i)
6.03 µs ± 26.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Jupyter Notebook 环境
%timeit ([i for i in range(100) if i % 2 == 0])
4.57 µs ± 26 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
newlist = [print(i) for i in range(5)]
print('newlist = {}'.format(newlist))
0
1
2
3
4
newlist = [None, None, None, None, None]
[i for i in range(20) if i % 2 == 0 and i % 3 ==0]
# [0, 6, 12, 18]
[i for i in range(20) if i % 2 == 0 if i % 3 ==0]
# [0, 6, 12, 18]
[(x, y) for x in 'abc' for y in range(2)]
# [('a', 0), ('a', 1), ('b', 0), ('b', 1), ('c', 0), ('c', 1)]
[[x, y] for x in 'abc' for y in range(2)]
# [['a', 0], ['a', 1], ['b', 0], ['b', 1], ['c', 0], ['c', 1]]
[{
x, y} for x in 'abc' for y in range(2)]
# [{0, 'a'}, {1, 'a'}, {0, 'b'}, {1, 'b'}, {0, 'c'}, {1, 'c'}]
[(i, j) for i in range(7) if i > 4 for j in range(20, 25) if j > 22]
[(i, j) for i in range(7) for j in range(20, 25) if i > 4 if j > 22]
[(i, j) for i in range(7) for j in range(20, 25) if i > 4 and j > 22]
# [(5, 23), (5, 24), (6, 23), (6, 24)]
list1 = [[1, 0] for x in 'abce' for y in range(2)]
print(list1)
for i in range(len(list1)):
print(id(list1[i]))
[[1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0], [1, 0]]
117234952
117235016
117235272
117235208
117235144
117235080
117235400
117235336
( 返回值 for 元素 in 可迭代对象 if 条件 )
从下面示例中可以总结出:
next(g)
获取for
可以遍历 生成器next()
会报错,使用 for
不会g = ('{:04}'.format(i) for i in range(5))
print(1, 'g is {}.'.format(g))
print(2, 'type(g) is {}.'.format(type(g)))
print(3, next(g))
for x in g:
print(x)
print('4============4')
for x in g:
print(x), type(x)
print('5============5')
print(6, next(g))
1 g is <generator object <genexpr> at 0x00000000077D9548>.
2 type(g) is <class 'generator'>.
3 0000
0001
0002
0003
0004
4============4
5============5
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-65-8121dfd1b116> in <module>
13 print('5============5')
14
---> 15 print(6, next(g))
StopIteration:
从下面示例中可以总结出:
g = ['{:04}'.format(i) for i in range(5)]
print(1, 'g is {}.'.format(g))
print(2, 'type(g) is {}.'.format(type(g)))
for x in g:
print(x)
print('3============3')
for x in g:
print(x), type(x)
print('4============4')
1 g is ['0000', '0001', '0002', '0003', '0004'].
2 type(g) is <class 'list'>.
0000
0001
0002
0003
0004
3============3
0000
0001
0002
0003
0004
4============4
{ 返回值 for 元素 in 可迭代对象 if 条件 }
set1 = {
(x, x+1) for x in range(5)}
print(set1, type(set1))
# {(0, 1), (1, 2), (4, 5), (2, 3), (3, 4)}
set2 = {
(i, j) for i in range(2) for j in range(2)}
print(set2, type(set2))
# {(0, 1), (1, 0), (0, 0), (1, 1)}
{
[x] for x in range(5)}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-69-a39ffa943c7e> in <module>
----> 1 {
[x] for x in range(5)}
<ipython-input-69-a39ffa943c7e> in <setcomp>(.0)
----> 1 {
[x] for x in range(5)}
TypeError: unhashable type: 'list'
{ 返回值 for 元素 in 可迭代对象 if 条件 }
key:value
形式{
x:(x, x+1) for x in range(3)}
# {0: (0, 1), 1: (1, 2), 2: (2, 3)}
{
x:[x, x+1] for x in range(3)}
# {0: [0, 1], 1: [1, 2], 2: [2, 3]}
{
(x, ):[x, x+1] for x in range(3)}
# {(0,): [0, 1], (1,): [1, 2], (2,): [2, 3]}
{
chr(0x41+x):x**2 for x in range(3)}
# {'A': 0, 'B': 1, 'C': 4}
{
str(x):y for x in range(3) for y in range(4)}
# {'0': 3, '1': 3, '2': 3}
# 字典赋值会进行覆盖
特殊的对象,一定是可迭代对象,具备可迭代对象的特征
通过 iter
方法把一个可迭代对象封装成迭代器
Docstring:
iter(iterable) -> iterator
iter(callable, sentinel) -> iterator
Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.
Type: builtin_function_or_method
通过 for
方法,迭代 迭代器对象
通过 next
方法,迭代 迭代器对象
生成器对象,也是 迭代器对象
从前到后走完一遍后,不能回头
如果 迭代器 已迭代完毕,使用 next()
会报错,使用 for
不会
iter1 = iter(range(3))
print(type(iter1))
print(iter1)
for i in iter1:
print(i)
print('==============')
for i in iter1:
print(i)
print('==============')
<class 'range_iterator'>
<range_iterator object at 0x0000000008328830>
0
1
2
==============
==============
iter2 = iter(list(range(3)))
print(type(iter2))
print(iter2)
print(1, next(iter2))
for i in iter2:
print(i)
print('==============')
print(next(iter2))
print('==============')
<class 'list_iterator'>
<list_iterator object at 0x00000000027CA308>
1 0
1
2
==============
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-107-d48de9f46b81> in <module>
6 print(i)
7 print('==============')
----> 8 print(next(iter2))
9 print('==============')
StopIteration:
list / tuple / string / bytes / bytearray / range / set / dict / 生成器 / 迭代器
in / not in
in
本质上对于线性结构就是在遍历对象,非线性结构求 hash
3 in range(5) # True
3 in (x for x in range(5)) # True
3 in {
x:y for x,y in zip(range(4), range(4, 10))} # True