新建列表
方法一:
1 2 3 4 5 6 7
| list = [None] * 4
list[0] = 'a' list[1] = 'b' list[2] = 'c' list[3] = 'd'
|
方法二:
1 2 3 4
| list = []
list.append('a')
|
添加列表元素
方法一:
1 2 3
| list = ['a','b','c','d'] list.append("e")
|
方法二:
1 2 3
| list = ['a','b','c','d'] list.extend("e","f")
|
方法三:
1 2 3
| list = ['a','b','c','d'] list.insert(2,"B")
|
总结:
append:在列表末尾添加单个元素;格式:list.append(value)
extend:在列表末尾添加多个元素;格式:list.extend(value)
insert:在列表指定位置插入元素;格式:list.insert(index,value)
修改列表元素
1 2 3
| list = ['a','b','c','d'] list.append[0] = 'A'
|
删除列表元素
方法一:
1 2 3
| list = ['a','b','c','d'] list.remove('a')
|
方法二:
1 2 3
| list = ['a','b','c','d'] del.list[0]
|
方法三:
1 2 3
| list = ['a','b','c','d'] list.pop()
|
总结:
remove:直接删除指定的元素;格式:list.remove(value)
del:根据索引位置删除元素;格式:del.list[index]
pop:根据索引位置删除元素;格式:list.pop(index)
列表切片
1 2 3 4 5 6 7 8 9 10 11
| list1 = ["汉堡", "比萨饼", "鸭肉卷", "鸡肉卷"] list2 = ["香辣鸡翅", "烤翅", "香骨鸡", "大排鸡"] list3 = ["红茶", "乌龙茶", "豆浆", "果汁", "可乐"] item1 = list1[2] print(item1) item2 = list2[2:] print(item2) item3 = list3[-1] print(item3) lists = [item1] + item2 + [item3] print(lists)
|
列表排序
正向排序:
1 2 3 4
| list = ["zip","apk","exe","py","xls","md"] list.sort() print(list)
|
反向排序:
1 2 3 4
| list = ["zip","apk","exe","py","xls","md"] list.sort(reverse=True) print(list)
|
临时排序:
1 2 3
| list = ["zip","apk","exe","py","xls","md"] print(sorted(list))
|
确定列表长度
1 2 3 4
| list = ["zip","apk","exe","py","xls","md"] long = len(list) print(long)
|
复制列表
1 2 3
| number = ["a","b","c"] a = number[:] print(a)
|
元组的创建和使用
定义:包含0个或多个元素的有序序列
格式:元组名=(value1,value2……)
特性:只能读取,不能修改
1 2 3 4 5
| score = (58,13,79,100,54,85,20,91) all = 0 for i in range(8): all = all + score[i] print("总分:",all)
|
End