列表
列表称之为容器型数据类型。
# li = [123, ‘老男孩‘, True, [1, 2, 3], {‘name‘: ‘alex‘}, (1, 2, 3)]
索引
# l1 = [‘wusir‘, True, ‘alex‘, ‘laonanhai‘, ‘ritian‘, ‘taibai‘]
# print(l1[0]) # print(l1[1], type(l1[1])) # 按照切片取值 # print(l1[:3]) # print(l1[2:]) # print(l1[::2])
增删改查以及其他方法
# 增
#append 追加
# print(l1.append(‘女神‘)) # l1.append(123) # l1.append([1, 2, 1111]) # print(l1) # name_list = [‘wusir‘, ‘alex‘, ‘laonanhai‘, ‘ritian‘, ‘taibai‘] # while True: # username = input(‘请输入新员工名字:Q或者q退出‘).strip() # if username.upper() == ‘Q‘: break # name_list.append(username) # print(‘您已经成功添加了%s‘ % username) # print(name_list)
#insert 插入
# l1.insert(1, ‘哪吒‘) # print(l1)
# extend 迭代着追加
# l1.extend(‘abcd‘) # l1.extend([1, 2, 3, 4, ‘abc‘]) # print(l1)
# 删
# pop 按照索引去删除, 有返回值
# ret = l1.pop(0) # print(ret) # print(l1)
# remove 按照元素删除
# l1.remove(‘alex‘) # print(l1)
# clear 清空列表
# l1.clear() # print(l1)
#del
‘‘‘ 1,在内存级别删除列表 del l1 print(l1) 2,按照索引删除。 del l1[2] print(l1) 3,切片删除+步长。 del l1[:-1] print(l1) ‘‘‘
# del l1 # print(l1) # del l1[2] # print(l1) # del l1[:-1] # print(l1) # del l1[:3:2] # print(l1)
# 改
# 1,按照索引去改。 # l1[0] = ‘肖锋‘ # print(l1) # l1[-1] = ‘男神‘ # print(l1) # 2,按照切片去改,先将切片的区域内的内容全部删除,在迭代着添加内容。 # l1[:3] = ‘范德萨发给ghfkhgh;‘ # l1[:3] = [1111, 2222, 3333, 4444] # print(l1)
# 查 按照索引切片去查
#for循环
# for i in l1: # print(i)
#其他操作方法:#len 个数
# cou = len(l1) # print(cou)
#count 元素个数
# print(l1.count(‘taibai‘))
#index 通过元素找索引
# print(l1.index(‘alex‘, 3)) # l2 = [1, 3, 5, 9, 7, 6, 2, 4]
#sort 从小到大,正序排序
# l2.sort() # print(l2)
#sort 从大到小,倒序排序
# l2.sort(reverse=True) # print(l2)
#翻转 reverse
# l2.reverse() # print(l2)
列表的嵌套
l1 = [‘wusir‘, ‘alex‘, [99, ‘ taibai‘, ‘98‘], 21]
# 1, 将wusir变成全部的大写。
# l1[0] = ‘WUSIR‘ # print(l1) # print(l1[0].upper()) # l1[0] = l1[0].upper() # print(l1)
# 2,将‘taibai‘变成首字母大写,其他字母小写,放回原处。
# print(l1[2]) # l2 = l1[2] # l2[1] = l2[1].strip().capitalize() # l1[2][1] = l1[2][1].strip().capitalize() # print(l1) # l1[2].append(‘舒淇‘) # print(l1)
# 3,用数字的相加将99 变成 字符串的 ‘100‘.
# l1[2][0] = str(l1[2][0] + 1) # print(l1)
# 4,字符串的‘98‘ 变成数字的100.
# l1[2][2] = int(l1[2][2]) + 2 # print(l1)
# 元组 只读列表,不能增删改 只能查询
# tu = (11, 22, 33, 44, 55)
#索引,切片,步长
# print(tu[0]) # print(tu[:3:2]) # for i in tu: # print(i)
# index len count
range
当做自定义的数字范围列表,# 满足顾头不顾腚,可以加步长,与for循环结合使用。
# for i in range(0, 101): #[0,1,2,3,....100] # print(i) # for i in range(11): # [0,1,2,3,....10] # print(i) # for i in range(0, 101, 3): # print(i) # for i in range(10, 0, -1): # print(i) # l1 = [22, 33, 33, 33, 66, 77, 88, 99] # for i in l1: # print(l1.index(i)) # for i in range(len(l1)): # print(i)
将l1 列表内所有元素打印,包括内部列表。
l1 = [‘wusir‘, ‘alex‘, [99, ‘ taibai‘, ‘98‘], 21] for i in l1: if type(i) == list: for j in i: print(j) else:print(i)
原文地址:https://www.cnblogs.com/HoneyTYX/p/8981352.html
时间: 2024-10-20 01:53:52