标签:python
1.切片
L = [‘Michael‘,‘Sarah‘,‘Tracy‘,‘Bob‘,‘Jack‘]
L[0:3] #从0开始索引,直到3,但不包括3,也就是0,1,2
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
L[:3] #如果索引从0开始,可以忽略
[‘Michael‘, ‘Sarah‘, ‘Tracy‘]
L[-1] #取倒数第一个元素
[‘Jack‘]
L = range(100)
L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
L[:10] #取前10个数
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
L[-10:] #取后10个数
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
L[10:20] #取10-20
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
L[:10:2] #前10个数,每2个取一个
[0, 2, 4, 6, 8]
L[::5] #所有数里面,每5个取一个
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
2.迭代
字典迭代
d = {‘a‘:1,‘b‘:2,‘c‘:3}
d
{‘a‘: 1, ‘c‘: 3, ‘b‘: 2}
for key in d:
print key
a
c
b
for key in d:
print key,d[key]
a 1
c 3
b 2
for value in d.itervalues(): #迭代values
print value
1
3
2
for k,v in d.iteritems(): #迭代k和v
print k,v
a 1
c 3
b 2
3.列表生成式
range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
L = []
for x in range(1,11):
L.append(x*x)
L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
L = [x*x for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
d = {‘x‘:‘A‘,‘y‘:‘B‘,‘z‘:‘C‘}
l = [k + ‘=‘ + v for k,v in d.iteritems()]
4.生成器
L = [x * x for x in range(10)]
L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
g = (x * x for x in range(10))
g
<generator object <genexpr> at 0x104feab40>
g.next() #取值
g = (x*x for x in range(10))
for n in g: #可以迭代,这种是最有效的方式
print n
本文出自 “八英里” 博客,请务必保留此出处http://5921271.blog.51cto.com/5911271/1795925
标签:python
原文地址:http://5921271.blog.51cto.com/5911271/1795925