列表 name = [‘kzx‘, ‘666‘, ‘none‘, ‘truth‘] # 截取 print(name[1: 3]) # 取下标1到3的元素(含下标1的元素,但是不包含3的)[‘666‘, ‘none‘]print(name[1:-1]) # 也是取下标1到-1(即下标3)的元素(含下标1的元素,但是不包含-1的) [‘666‘, ‘none‘] print(name[0:3]) # 取下标0到3的元素(含下标1的元素,但是不包含3的)[‘kzx‘, ‘666‘, ‘none‘]print(name[:3]) # 也是取下标0到3的元素[‘kzx‘, ‘666‘, ‘none‘] print(name[1:]) # 取除下标0外所有的元素 [‘666‘, ‘none‘, ‘truth‘] print(name[1: 4]) # 当下标大于该列表的最大下标时,等价于name[start,max] # (start即开始取的下标,max即该列表最大的下标) [‘666‘, ‘none‘, ‘truth‘] # 添加 name.append("new") # 从最后添加 name.insert(2, "插入") print(name) [‘kzx‘, ‘666‘, ‘插入‘, ‘none‘, ‘truth‘, ‘new‘] # 修改 name[2] = "change" print(name) [‘kzx‘, ‘666‘, ‘change‘, ‘none‘, ‘truth‘, ‘new‘] # 删除 del name[2] # 删除列表下标为2的元素 name.remove("kzx") # 指定删除元素 print(name) [‘666‘, ‘none‘, ‘truth‘, ‘new‘] name.pop() # 删除列表最后一个值 # 合并2个列表 b = [1, 2, 3] name.extend(b) print(name) [‘666‘, ‘none‘, ‘truth‘, 1, 2, 3] # copy copy_name = name.copy() print(copy_name) [‘666‘, ‘none‘, ‘truth‘, 1, 2, 3] # 统计元素出现次数 names = [‘kkk‘, ‘rr‘, ‘kkk‘, ‘e‘, ‘rr‘, 1, 2, 3] print(names.count("kkk")) 2 # 排序 c = [1, 2, 3] c.sort() print(c) # python3里不同数据类型不能放在一起排序 [1, 2, 3] c.reverse() print(c) # 反转[3, 2, 1]
# 获取下标 print(names.index("kkk")) # 只返回找到的第一个下标 0
字典
dic = {‘name‘: ‘a‘, ‘age‘: 21, ‘gender‘: ‘middle‘} # 添加 dic[‘habbit‘] = ‘a_lot‘ print(dic) {‘name‘: ‘a‘, ‘gender‘: ‘middle‘, ‘habbit‘: ‘a_lot‘, ‘age‘: 21} # 修改 dic[‘habbit‘] = ‘none‘ print(dic) {‘name‘: ‘a‘, ‘gender‘: ‘middle‘, ‘habbit‘: ‘none‘, ‘age‘: 21} # 删除 dic.pop(‘habbit‘) # or use (del dic[‘habbit‘]) print(dic) {‘name‘: ‘a‘, ‘gender‘: ‘middle‘, ‘age‘: 21} # 查找 print(‘age‘ in dic) True print(dic.get(‘age‘)) # or use (dic[‘age‘]) 21 # others print(dic.values()) print(dic.keys()) dict_values([‘a‘, ‘middle‘, 21]) dict_keys([‘name‘, ‘gender‘, ‘age‘]) # 遍历 # 方法1 for key in dic: print(key, dic[key]) # 方法2 for k, v in dic.items(): # 会先把dict转成list,数据里大时莫用 print(k, v)
弱渣的我介绍一下python3的列表和字典,还有稍微提一下元组
关于元组
names
=
(
"al"
,
"u"
,
"c"
)
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
[1, 2, 3][3, 2, 1]
原文地址:https://www.cnblogs.com/truthk/p/8453632.html
时间: 2024-11-12 01:11:46