练习五十八:列表的练习

原文链接: http://www.cnblogs.com/pinpin/p/10233813.html

部分的python中list的练习实例

>> dir(list)
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

实例:

testlist =  [12306,"购票系统",[1,2,3,0,6]]  #建立列表
print(len(testlist))#列表长度len()
print(testlist[1:]) #从索引位置开始到结束的列表
testlist.append('有钱没钱回家过年')#列表尾部添加元素
testlist.insert(0,'home') #索引位置添加元素,后面元素想后移动
print(len(testlist))
print(testlist[-1])#打印最后一个元素
print(testlist.pop(1)) #弹出索引为1的元素
print(len(testlist))
testlist.reverse() #列表反转
print(testlist)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print(matrix) #打印列表
print(matrix[1]) #打印列表中索引为1的元素
print(matrix[1][1]) 
col1 = [row[1] for row in matrix]  #每行元素中的索引为1的元素
print(col1)
col2 = [row[1] for row in matrix if row[1]%2==0 ]   #每行元素中的索引为1的元素,且元素是偶数
print(col2)
col1.extend(col2) #将col2添加到col1中
print(col1,col2)

执行结果:

3
['购票系统', [1, 2, 3, 0, 6]]
5
有钱没钱回家过年
12306
4
['有钱没钱回家过年', [1, 2, 3, 0, 6], '购票系统', 'home']
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[4, 5, 6]
5
[2, 5, 8]
[2, 8]
[2, 5, 8, 2, 8] [2, 8]

转载于:https://www.cnblogs.com/pinpin/p/10233813.html

猜你喜欢

转载自blog.csdn.net/weixin_30888413/article/details/94790131