python学习
range()函数
range(5) -> 0、1、2、3、4
range(5,9) -> 5、6、7、8
range(0,10,3) -> 0、3、6、9 :步长为3
列表
在内存中,序列是一块用来存储多个值的连续的内存空间。
一个对象包含:内存地址id,数据类型type,数值value三部分,序列中存储的是对象的id。
列表索引,从前往后,下标从0开始,从后往前,下标从-1开始。
list.append(obj) #在列表末尾添加新的对象
list.extend(seq) #在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.count(obj) #统计某个元素在列表中出现的次数
list.index(obj) #从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj) #将对象插入列表index位置
list.pop([index=-1]) #移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) #移除列表中某个值的第一个匹配项
list.sort( key=None, reverse=False) #对原列表进行排序
list.clear() #清空列表
list.copy() #复制列表,返回列表对象的浅拷贝
list.reverse() #所有元素原地翻转
append()方法是原地增加元素,列表内存地址不变
>>> list2=[x**2 for x in range(10) if x&1==1]
>>> list2
[1, 9, 25, 49, 81]
>>> id(list2)
22112552
>>> list2.append(2)
>>>> list2
[1, 9, 25, 49, 81, 2]
>>> id(list2)
22112552
+运算使用新内存地址,而+=运算仍使用原内存地址
>>> list3
[1, 2, 3, 4, 5]
>>> id(list3)
22111464
>>> list3+=[6]
>>> list3
[1, 2, 3, 4, 5, 6]
>>> id(list3)
22111464
>>> list3=list3+[7]
>>> list3
[1, 2, 3, 4, 5, 6, 7]
>>> id(list3)
22069096
extend()方法是原地操作,内存地址不变。效率高于+运算的拼接操作。
>>> list3.extend([9,10])
>>> list3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> id(list3)
22069096
列表删除:
del 直接删除
del list[2]
pop() 删除并返回,如未指定位置,默认删除最后一个元素
>>> list4=[1,2,3,4]
>>> list4
[1, 2, 3, 4]
>>> del list4[2]
>>> list4
[1, 2, 4]
>>> list4.pop()
4
>>> list4
[1, 2]
remove()方法,删除首次出现的指定元素,若不存在,抛出异常。
>>> list5=[1,2,3,4,5,4,3,2]
>>> list5.remove(2)
>>> list5
[1, 3, 4, 5, 4, 3, 2]
>>> list5.remove(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
列表索引:
index()方法,获取指定元素首次出现的位置,可指定搜索的起始地址。
def index(self, *args, **kwargs): # real signature unknown
"""
Return first index of value.
Raises ValueError if the value is not present.
"""
pass
>>>list1=[1,2,3,4,5,3,4,6]
>>>print(list1.index(3,4))
不建新对象的列表排序:
>>> list6=[1,6,4,9,20,8,3]
>>> id(list6)
22112616
>>> list6.sort()
>>> list6
[1, 3, 4, 6, 8,