>>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100]
>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
>>> import os
>>> [d for d in os.listdir('.')]
['README.md', '.git', 'image', 'os', 'lib', 'sublime-imfix', 'src']
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']
>>> L = ['Hello', 'World', 'IBM', 'Apple'] >>> [s.lower() for s in L] ['hello', 'world', 'ibm', 'apple']
>>> L = ['Hello', 'World', 'IBM', 'Apple', 12, 34] >>> [s.lower() if isinstance(s,str) else s for s in L] ['hello', 'world', 'ibm', 'apple', 12, 34]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
list(range(1, 11))
# 生成1乘1,2乘2...10乘10
L = []
for x in range(1, 11):
L.append(x * x)
# 上面太麻烦,看下面
[x * x for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 加上if,就可以筛选出仅偶数的平方
[x * x for x in range(1, 11) if x % 2 == 0]
# [4, 16, 36, 64, 100]
# 两层循环,可以生成全排列
[m + n for m in 'ABC' for n in 'XYZ']
# ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
# 列出当前目录下的所有文件和目录名
import os
[d for d in os.listdir('.')] # on.listdir可以列出文件和目录
# 列表生成式也可以使用两个变量来生成list:
d = {'x': 'A', 'y': 'B', 'z': 'C'}
[k + '=' + v for k, v in d.items()]
# ['x=A', 'z=C', 'y=B']
# 把一个list中所有的字符串变成小写
L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L]
# ['hello', 'world', 'ibm', 'apple']
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s, str)]
print(L2)
# ['hello', 'world', 'apple']
# isinstance函数可以判断一个变量是不是字符串
>>> g = (x * x for x in range(10)) >>> g <generator object <genexpr> at 0x7fe73eb85cd0>
>>> g.next() 0 >>> g.next() 1 >>> g.next() 4 >>> g.next() 9 >>> g.next() 16 >>> g.next() 25 >>> g.next() 36 >>> g.next() 49 >>> g.next() 64 >>> g.next() 81 >>> g.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
>>> g = (x * x for x in range(10)) >>> for n in g: ... print n ...
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
>>> fib(6) <generator object fib at 0x7fa1c3fcdaf0> >>> fib(6).next() 1
def odd(): print 'step 1' yield 1 print 'step 2' yield 3 print 'step 3' yield 5
>>> o = odd() >>> o.next() step 1 1 >>> o.next() step 2 3 >>> o.next() step 3 5 >>> o.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
def odd():
print 'step 1'
yield 1
print 'step 2'
yield 2
print 'step 3'
yield 3
if __name__ == '__main__':
o = odd()
while True:
try:
print o.next()
except:
break
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有