列表可一次性存多个不同类型的数据,数据之间用,隔开,可修改
- 常见操作:
list1 = [1,(1,2,3),'d']
list2 = [4,5,6]
print(list1[0],list1[-1],list1[1:])
print(len(list1))#列表长度
print(list1 + list2)#列表组合
print(list1*3)#列表重复
print(1 in list1)
print('z' not in list1)#判断元素是否在列表里返回True/False
for i in list1:#列表遍历
print(i)
#1 d [(1, 2, 3), 'd']
#3
#[1, (1, 2, 3), 'd', 4, 5, 6]
#[1, (1, 2, 3), 'd', 1, (1, 2, 3), 'd', 1, (1, 2, 3), 'd']
#True
#True
#1 (1, 2, 3) d
- 常见函数
list.append(obj) 追加把整体作为list的一个元素
list.extend(obj) 追加追加另一个序列的所有元素分别追加
list.insert(index,obj) 将obj插入到列表给定位置
list1 = ['a','b','c']
list1.append([1,2,3])
print(list1)
list1.extend([4,5,6])
print(list1)
list1.insert(0,'aa')
print(list1)
#['a', 'b', 'c', [1, 2, 3]]
#['a', 'b', 'c', [1, 2, 3], 4, 5, 6]
#['aa', 'a', 'b', 'c', [1, 2, 3], 4, 5, 6]
list.count(obj) obj在列表中出现的次数
del(obj) 或del obj 既可以删除指定元素也可以删除列表 del(list[0]) del(list)
list1 = ['a','b','c']
print(list1.count('a'))
del list1[2]
print(list1)
del(list1[0])
print(list1)
del(list1)
print(list1)
#1
#['a', 'b']
#['b']
#NameError: name 'list1' is not defined
list.pop(index) 删除指定下标元素,返回该元素的值,若无下标默认列表最后一个元素
list.remove(obj) 移除列表中obj第一个匹配值
list.clear() 清空列表
list1 = ['a','b','c']
a = list1.pop(0)#有返回值
print(a,list1)
b = list1.remove('c')
print(b)#打印None
print(list1)
list1.clear()
print(list1)
#a ['b', 'c']
#None
#['b']
#[]
list.reverse() 列表倒序
list.sort(reverse = bool) True时从大到小排序
max(list)/min(list) 返回列表中最大值和最小值
list1 = ['a','b','c']
list1.reverse()
print(list1)
list1.sort()#默认由小到大
print(list1)
list1.sort(reverse = True)
print(list1)
print(max(list1))
print(min(list1))
#['c', 'b', 'a']
#['a', 'b', 'c']
#['c', 'b', 'a']
#c
#a
本文介绍了Python中列表的使用,包括存储多种类型数据、常用操作如append、extend、insert等,以及如何计数、删除、排序和翻转列表元素。通过这些函数和方法,可以高效地管理和操作列表内容。

4189

被折叠的 条评论
为什么被折叠?



