Driver Into Python 学习摘要 第三章

List的赋值:

1
2
3
4
5
6
"""s[i:j] = t
slice of s from i to j is replaced by the contents of the iterable t"""
li = ["a",2,True,"b"]
li[4:5] = ["c",False,3] #批量赋值,超过范围自动扩展List大小
print li
>>[‘a‘, 2, True, ‘b‘, ‘c‘, False, 3]

List的索引: 

1
2
3
4
5
6
7
8
9
10
11
12
li = ["a","b","c","d","e"]
 
print li[1] #返回索引值为1的项
>>"b"
print type(li[2]) #返回的类型为str型<br>>><type ‘str‘>
print li[-4] #任何一个非空的list最后一个元素总是li[-1]<br>>>"b"
print li[1:2]#分片返回索引值从1到1的值<br>>>[‘b‘]
print type(li[1:2])<br>>><type ‘list‘> #返回的类型为List类型
print li[:2]#slice简写,当左侧分片索引为空时默认为0
>>[‘a‘, ‘b‘]
print li[1:] #简写,当右侧分片索引为空时,默认为list的长度<br>>>[‘b‘, ‘c‘, ‘d‘, ‘e‘]
print li[:] #等于 print li[0:len(li)]<br>>>[‘a‘,‘b‘, ‘c‘, ‘d‘, ‘e‘]

List中添加元素:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
li = ["a","b","c","d","e"]
li.append("f")
print li
>>[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
li.insert(2,"1")
print li
>>[‘a‘, ‘b‘, ‘1‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘]
li.extend(["g","h"])
print li
>>[‘a‘, ‘b‘, ‘1‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘]
 
#append与extend的区别
 
li = ["a","b","c","d","e"]
li.extend(["f","g"])
print li
>>[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘]
li.append(["f","g"])
print li
>>[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, [‘f‘,‘g‘]]

List中搜索:

1
2
3
4
5
6
7
8
9
"""s.index(x[, i[, j]])
return smallest k such that s[k] == x and i <= k < j"""
"""返回值li[i]到li[j]之间值等于x的最小k值"""
 
li = ["a",2,True,"b",2]
print li.index(2)
>>0
print li.index(2,2)
>>4

Count函数:

1
2
3
4
5
"""s.count(x)
return number of i‘s for which s[i] == x"""
"""返回x值在List中出现的次数"""
li = ["a",2,True,"b",2]
print li.count(True)

pop函数:

1
2
3
4
5
6
7
8
9
10
"""s.pop([i])
same as x = s[i]; del s[i]; return x"""
"""s.pop(i)
删除s中s[i],并返回该值"""
 
li = ["a",2,True,"b",2]
print li.pop(4)
print li
print li.pop()
print li

从List中删除元素:

Driver Into Python 学习摘要 第三章,布布扣,bubuko.com

Driver Into Python 学习摘要 第三章

上一篇:批量修改线上配置文件 python版


下一篇:C++ STL示例