零基础学python-8.4 在原处修改列表方法汇总
1.索引和切片,通过索引和切片,将相应的值取出来,然后替换成新的值>>> aList=['123',123,'a']
>>> aList=1
>>> aList
>>> aList=
>>> aList
>>> 下面举一个利用切片调换值的例子
>>> aList=['123',123,'a']
>>> aList=aList
>>> aList
>>>
上面方法的执行顺序是:(对于aList=aList) 1)先把aList所对应的值取出来
2)删除aList的值
3)把aList替换到aList上
2.使用列表方法替换
1)使用append与+
使用append
>>> aList=['123',123,'a']
>>> aList.append (234)
>>> aList
['123', 123, 'a', 234]
>>>
>>> aList=['abA','ABb','aBC','Abd',123]
>>> aList.append (['123'])
>>> aList
['ABb', 'Abd', 'aBC', 'abA', 123, ['123']]
>>>
使用+
>>> aList=['123',123,'a']
>>> aList+
['123', 123, 'a', 234]
>>> 结果是一样的,而且都是原处修改
>>> aList=['123',123,'a']
>>> id(aList)
36649920
>>> aList.append (234)
>>> id(aList)
36649920
>>> aList+['efg']
['123', 123, 'a', 234, 'efg']
>>> id(aList)
36649920
>>>
通过上面的代码可以看见,id始终没有变化,也就是说aList没有创建新的对象,都是使用同一个对象
3.排序
>>> aList=['abA','ABb','aBC','Abd']
>>> aList.sort ()
>>> aList
['ABb', 'Abd', 'aBC', 'abA']
>>> aList.sort (key=str.lower ,reverse=True)
>>> aList
['Abd', 'aBC', 'ABb', 'abA']
>>> aList.sort (key=str.upper,reverse=True)
>>> aList
['Abd', 'aBC', 'ABb', 'abA']
>>> aList.sort (key=str.upper,reverse=False)
>>> aList
['abA', 'ABb', 'aBC', 'Abd']
>>> 通过改变sort里面的参数,使得aList 的排序方式发生改变 注意:排序是对于同一类型对象的,不同类型的对象不能排序
>>> aList=['abA','ABb','aBC','Abd',123]
>>> aList.sort ()
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
aList.sort ()
TypeError: unorderable types: int() < str()
>>>
4.其他的一些方法
>>> aList=['abA','ABb','aBC','Abd',123]
>>> aList.pop (4)
123
>>> aList
['abA', 'ABb', 'aBC', 'Abd']
>>> aList.reverse ()
>>> aList
['Abd', 'aBC', 'ABb', 'abA']
>>> aList.index ('aBC')
1
>>> aList.insert (2,'efg')
>>> aList
['Abd', 'aBC', 'efg', 'ABb', 'abA']
>>> del aList
>>> aList
['Abd', 'aBC', 'efg', 'abA']
>>>
就说到这里,谢谢大家
------------------------------------------------------------------
点击跳转零基础学python-目录
版权声明:本文为博主原创文章,未经博主允许不得转载。
页:
[1]