列表
元素存取
list = []
list.append('a') #列表末尾添加元素
list.append('b')
print(list) # 结果 ['a', 'b']
list.insert(0,'c') #列表中插入元素
print(list) # 结果 ['c', 'a', 'b']
list[0]='a' #列表元素修改
print(list) # 结果 ['a', 'a', 'b']
del list[0] #根据元素位置删除元素
print(list) # 结果 ['a', 'b']
poped_list = list.pop() #弹出元素,默认为列表末尾,可以使用pop(0)来指定元素位置
print(poped_list ) #结果 b
print(list) #结果['a']
list.remove('a') # 根据值删除元素
print(list) #结果 []
组织列表
list = ['a','b','c','d']
len_list = len(list) #确定列表长度
print(len_list) #结果 4
list.sort() #永久排序
print(list) #结果 ['a', 'b', 'c', 'd']
list = ['a','b','d','c']
print(sorted(list)) #临时排序 ['a', 'b', 'c', 'd']
print(list) #结果 ['a', 'b', 'd', 'c']
list.sort(reverse=True) #倒序
print(list) #结果 ['d', 'c', 'b', 'a']
list.reverse() #反转
print(list) #结果 ['d', 'c', 'b', 'a']
遍历
lists = ['a','b','c']
for list in lists:
print(list)
创建数字列表
for value in range(1,3):
print(value)
#结果
1
2