1、列表的定义
列表是按照特定的顺序排列的元素的集合,列表的元素可以是数字、字符串等类型,元素之间用逗号隔开。
例子:example = [‘a’,1,“python”,5]
2、列表的创建
temp = [] #直接用方括号创建
temp2 = list() #用list方法创建
3、列表的基本操作
例子:temp = [“hello”,“world”,5,“A”,“B”]
temp = ["hello","world",5,"A","B"]
print(temp[1])
print(temp[-1])
world
B
temp[0] = "welcome"
print(temp)
['welcome', 'world', 5, 'A', 'B']
temp.append("C")
print(temp)
['D', 'welcome', 'world', 5, 'A', 'B', 'C']
temp.insert(0,"D")
print(temp)
['D', 'welcome', 'world', 5, 'A', 'B', 'C']
temp.insert(5,"B")
del temp[6]
print(temp)
['D', 'welcome', 'world', 5, 'A', 'B']
print(temp)
['A', 'welcome', 'D']
列表中常用的方法:
(1)remove() 删除元素
(2)sort() 元素排序(改变原来的元素顺序)
(3)sorted() 元素排序(不改变原来的元素顺序)
(4)reverse() 逆序排序
(5)len 求列表中元素的个数
(6)切片的操作
temp = ['a','b','c','d','e','f','g']
temp.remove('g')
temp
['a', 'b', 'c', 'd', 'e', 'f']
a = [1,32,3,4,44]
a.sort()
a
[1, 3, 4, 32, 44]
temp3 = [1,5,3,4,2]
sorted(temp3)
[1, 2, 3, 4, 5]
temp3
[1, 5, 3, 4, 2]
len(temp3)
5
列表中的切片的操作
temp =['hello','world','a','b',1,2]
temp[1:4]
['world', 'a', 'b']
temp[1:5:2]
['world', 'b']
temp[::-1]
[2, 1, 'b', 'a', 'world', 'hello']
temp[1:3] = []
temp
['hello', 'b', 1, 2]
list1 = ['huanle','lu','nihao','zuijinzayanga']
print(list1)
print(list1[1])
print(list1[-1])
print(list1[1:3])
print(list1[-3:-1])
list1[1] = 'liu'
print(list1[1])
print('=============')
for i in list1:
print(i)
if 'liu' in list1:
print('存在')
print(len(list1))
list1.append('你是好人啊')
print(list1)
list1.insert(1,'wenhui')
print(list1)
list1.pop()
print(list1)
list1.remove('nihao')
print(list1)
del list1[1]
print(list1)
list1.clear()
print(list1)
list1 = ['huanle','lu','nihao','zuijinzayanga']
list2 = list1.copy()
print(list2)
lt = list(list1)
print(lt)
list3 = list1 + lt
print(list3)
list3.extend(lt)
print(list3)
欢乐 = list(('你好啊','加油啊'))
print(欢乐)