Python:列表list方法 ①list.append() ②list.count() ③list.extend() ④list.index() ⑤list.insert(index, obj)

①list.append()
在列表末尾添加元素

aList = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
print "Updated List : ", aList;

结果

Updated List :  [123, 'xyz', 'zara', 'abc', 2009]

②list.count()
统计目的元素在列表中出现的次数

aList = [123, 'xyz', 'zara', 'abc', 123];
print "Count for 123 : ", aList.count(123);
print "Count for zara : ", aList.count('zara');

结果

Count for 123 :  2
Count for zara :  1

③list.extend()
在列表末尾一次性添加另一个列表的所有元素(列表扩展)

aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)

print "Extended List : ", aList ;

结果

Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

④list.index()
对元素在列表中进行索引,返回元素在列表的位置

aList = [123, 'xyz', 'zara', 'abc'];

print "Index for xyz : ", aList.index( 'xyz' ) ;
print "Index for zara : ", aList.index( 'zara' ) ;

结果

Index for xyz :  1
Index for zara :  2

⑤list.insert(index, obj)
插入元素到列表中

aList = [123, 'xyz', 'zara', 'abc']

aList.insert( 3, 2009)

print "Final List : ", aList

结果

Final List : [123, 'xyz', 'zara', 2009, 'abc']

引用:www.runoob.com/python/python-lists.html

猜你喜欢

转载自blog.csdn.net/qq_24182661/article/details/81324763