切片
1.取list或tuple前n个元素
L = [‘qwe’,‘asd’,‘asd’]
L
[‘qwe’, ‘asd’, ‘asd’]
//方法1[L[0],L[1]]
[‘qwe’, ‘asd’]
//方法2r = []
n = 2
for i in range(2):
… r.append(L[i])
…r
[‘qwe’, ‘asd’]
方法3:使用slice运算符
L[0:2]
[‘qwe’, ‘asd’]L[:2]
[‘qwe’, ‘asd’]
从0开始一直到2 (不包括2) ,若开始为0 则可以省略
倒数第一个索引为-1
L[-1:]
[‘zcv’]L[-1:]
[‘zcv’]L[-2:]
[‘asd’, ‘zcv’]L[-3:]
[‘qwe’, ‘asd’, ‘zcv’]
常见的切片操作
L = list(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,
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]L[-10:-15]
[]L[-10:-5]
[90, 91, 92, 93, 94]L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]L[0:10:2]
[0, 2, 4, 6, 8]L[0:10:5]
[0, 5]L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]L[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
tuple也可以进行切片操作,切片的结果仍为tuple
(1,2,3,4,5,6)[:2]
(1, 2)
字符串的切片 类似于字符分割函数
‘ABCDEFG’[:3]
‘ABC’‘ABCDEFG’[::2]
‘ACEG’
迭代
- for … in
d = {‘a’: 1, ‘b’: 2, ‘c’: 3}
for key in d:
… print(key)
…
a
c
bfor value in d:
… print(value)
…
a
b
cfor value in d.values():
… print(value)
…
1
2
3for k,v in d.items():
… print(k,v)
…
a 1
b 2
c 3
字符串也可以进行迭代
for ch in ‘ABC’:
… print(ch)
…
A
B
C
判断一个对象是否为可迭代对象
使用collections模块的Iterable
>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
打印两个参数,使用enumerate函数把一个list变成索引-元素对
>>> for i, value in enumerate(['A', 'B', 'C']):
... print(i, value)
...
0 A
1 B
2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
... print(x, y)
...
1 1
2 4
3 9