Universal list
Beginner python, a collection of our most frequently used data, the list is ordered, repeatable elements, sets, lists a series of elements that can be changed with a strong flexibility, while at the same time ensure these characteristics, the list of relative need more memory space. So the set is a good fit for our collection. Here we look at in the list of methods.
'''列表的构造方法'''
names= [ ] 一个空列表
naems= list ( ) 用列表构造函数创建一个列表
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
list 列表构造函数会迭代每一个传入的元素创建列表
bugs= list ( '12345' )
== = > [ '1' , '2' , '3' , '4' , '5' ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
names. append( 'james' )
给列表添加元素,总是在最右侧添加。
== = > [ 'james' ]
那么append可以一次添加多个元素嘛?
names. append( 'abc' , 'def' )
== >
TypeError: append( ) takes exactly one argument ( 2 given)
出现了错误,append只能接受一个参数。那我们更改以下传入参数。
names. append( ( 'abc' , 'def' ) )
[ 'james' , ( 'abc' , 'def' ) ]
可以看见作为一个元素被添加进了列表。
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
那么有没有可以一次性传入多个值的方法呢?
bugs= [ ]
bugs. extend( ( 'er' , 'or' , 'and' , 'True' , 'False' ) )
== > [ 'er' , 'or' , 'and' , 'True' , 'False' ]
extend( ) 方法会把传入的集合迭代每一个元素添加进列表。
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
names= [ ]
names. insert( 0 , '小红' )
names. insert( 0 , '小丽' )
== > [ '小丽' , '小红' ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
names. remove( '小丽' ) - 从列表中移除元素
names. clear( ) 清空列表, 当然你也可以再次赋值成names = [ ]
== > [ ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
numbers= [ 78 , 56 , 43 , 11 , 5 , 4 , 3 , 2 , 1 ]
print ( numbers. pop( ) )
print ( numbers. pop( 0 ) )
== > [ 56 , 43 , 11 , 5 , 4 , 3 , 2 , ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
想要倒序排列列表
numebers. reverse( ) == > [ 2 , 3 , 4 , 5 , 11 , 43 , 56 ]
想获得元素的下标
numbers. index( 3 ) == > 1
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
有时候我们会有一个杂乱无章的列表例如:
names= [ 'lili' , 'james' , 'alex' , 'bob' , 'bond' ]
我们想要给他排一下序
names. sort( )
== > [ 'alex' , 'bob' , 'bond' , 'james' , 'lili' ]
返回值为None , 但是列表已经被原地排序了, 默认为升序
names. sort( reverse= True )
更改参数为 True 变为降序排列
== > [ 'lili' , 'james' , 'bond' , 'bob' , 'alex' ]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
想获得列表中某一元素的个数
numbers= [ 1 , 1 , 1 , 1 , 3 , 4 , 4 , 5 , 6 , 7 , ]
numbers. count( 1 )
== > 4
在以上方法中需要注意的是,排序方法的返回值是None
所以当你:names= old_name. sort( ) , print ( names) 时,
names的值是None , 因为sort()排序是原地修改了列表,
原列表old_name已经改变成排序后的样子。