标签:int 方法 extend rem 关于 insert 方向 end 序列
1.创建列表
创建一个列表,只需要用逗号把数据分隔起来再加上方括号即可,例如
#访问列表中的值,列表中元素按下标为0开始计数
list1=["name","age","stu_num"]
list2=[1,2,3,4,5,6]
print("list1[0]" list1[0])# 按下标找到相应列表的值
print("list2[1:5]"stu_list[1:5])#打印下标从1到5的值但是不包括下标为5的元素
实际输出结果为:list1[0]:name
list2[2:5]:[3,4,5]
2.更新列表
list1=["name","age","come from"]
print(list1)#便于列表更新之后作比较
list1[2]="23"
print(list1)
输出结果:["name","23","come from"]
关于list的方法
(1)list.append(obj)#在列表末尾添加一个新对象
list=["a","b","c"]
list.append("welcome")
print(list)
输出结果为:["a","b","c","welcom"]
(2)list.count(obj)统计某个元素在列表中出现的次数
list=["a","b","c"]
print(list.count("a"))
输出结果为:1
(3)list.extend(seq)在列表末尾一次性追加列一个序列中的多个值
list=["a","b","c"]
list1=[1,2,3,4]
list.extend(list1)
print(list)
输出结果:["a","b","c","d",1,2,3,4]
(4)list.index(obj)从列表中找出第一个匹配项的索引位置
list=["a","b","c"]
print(list.index("b"))
输出结果:1
(5)list.insert(index,obj)将对象插入到列表中
list=["a","b","c"]
list.insert(1,"e")
print(list)
输出结果:[a,e,b,c]
(6)list.pop(obj=list[-1])移除列表中的一个元素,默认是最后一个元素,并且返回该元素的值
list=["a","b","c"]
print(list.pop())
print(list.pop(0))
ptint(list)
输出结果:c
[a,b]
(7)list.remove(obj)移除列表中某个值的第一个匹配项
list=["a","b","c","name","age","city"]
list.remove("name")
print(list)
输出结果:list=["a","b","c","age","city"]
(8)list.reverse()方向列表中的元素
list=["a","b","c","name","age","salary"]
list.reverse()
print(list)
(9)list.sort(func())对原列表进行排序
list=["a","b","c","1name","#age","salary"]
list.sort()
print(list)
输出结果:[‘#age‘, ‘1name‘, ‘a‘, ‘b‘, ‘c‘, ‘salary‘]
标签:int 方法 extend rem 关于 insert 方向 end 序列
原文地址:http://www.cnblogs.com/jiaxin1N/p/7857100.html