1.定义:
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可,序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
# 列表 list1=["liuhu","love","xiaoyunna"] list2=["yeah",520,888,"刘虎","肖云娜"] list3=list1+list2 #拼接 list4=[list1,list2] #嵌套列表
print(list3) print(list4) 输出:
['liuhu', 'love', 'xiaoyunna', 'yeah', 520, 888, '刘虎', '肖云娜']
[['liuhu', 'love', 'xiaoyunna'], ['yeah', 520, 888, '刘虎', '肖云娜']]2.访问或取值
print("list1[0]:",list1[0]) print("list2[1:3]:",list2[1:3]) print("list4[0]:",list4[0]) print("list4[0][1]:",list4[0][1])
print("list2[1:]:",list2[1:]) #输出从第二个元素开始后的所有元素 print("list2[-2]:",list2[-2]) #从右侧开始读取倒数第二个元素:
输出
list1[0]: liuhu
list2[1:3]: [520, 888]list4[0]: ['liuhu', 'love', 'xiaoyunna']list4[0][1]: lovelist2[1:]: [520, 888, '刘虎', '肖云娜']
list2[-2]: 刘虎3.添加
(1)list.append(object) #后追加元素
list1.append("520") print(list1) 输出: list1: ['liuhu', 'love', 'xiaoyunna', '520']
(2)list.insert(k,object) #指定k+1位置插入
list2.insert(0,"love") print("list2:",list2) 输出: list2: ['love', 'yeah', 520, 888, '刘虎', '肖云娜']
(3)后面批量添加
list.extend()list5=[1,2,3] list6=["liuhu",520] list5.extend(list6) print("list5:",list5) 输出: list5: [1, 2, 3, 'liuhu', 520] (4)拼接 (见定义)
4.删除
(1)del list[1:3] #删除指定索引位置内容
list2=["yeah",520,888,"刘虎","肖云娜"] del list2[1:3] print("list2:",list2) 输出: list2: ['yeah', '刘虎', '肖云娜']
(2)list.pop() #去除最后一个,列表返回剩余数据
list2=["yeah",520,888,"刘虎","肖云娜"] list2.pop() print("list2:",list2) 输出: list2: ['yeah', 520, 888, '刘虎']
(3)list.pop(k) #取出列表第K+1个
list2=["yeah",520,888,"刘虎","肖云娜"] list2.pop(2) print("list2:",list2) 输出: list2: ['yeah', 520, '刘虎', '肖云娜']
(4)list.remove(object) #去除左边查找匹配的一个
list7=["yeah",520,888,"刘虎","肖云娜",888] list7.remove(888) print("list7:",list7) 输出: list7: ['yeah', 520, '刘虎', '肖云娜', 888]
5.其他
(1)list.reverse() #反转
list2=["yeah",520,888,"刘虎","肖云娜"] list2.reverse() print("list2:",list2) 输出: list2: ['肖云娜', '刘虎', 888, 520, 'yeah']
(2)list.sort() #排序
list2=["yeah","" ,"/n","刘虎","肖云娜","6"] list2.sort() print("list2:",list2) 输出; list2: ['', '/n', '6', 'yeah', '刘虎', '肖云娜']
(3)list.count(object) #元素出现的次数
list2=["yeah","" ,"/n","刘虎","肖云娜","6"] m=list2.count("6") print(m) 输出: 1
(4)list.index() #元素位置索引
list2=["yeah",520,888,"刘虎","肖云娜"] n=list2.index(888) print("888位于:",n) 输出: 888位于: 2