Python----list,dict,tuple
2017-10-23 16:50
393 查看
List
列表中可以存储不同类型的数据, 但在使用场景中,列表一般都存储相同类型的数据list1 = ['tom', 'jack', 'rose'] list1.index('jack') # 返回数据的索引 # 增加 list1.insert(1, 'json') # 从指定的位子插入 list1.append('json') # 从尾部添加 list2 = ['admin'] list1.extend(list2) # 将列表2追加到列表中 # 删除 del list1[0] # 按索引从内存中删除 list1.remove('tom') # 删除指定的元素。 第一次出现的数据 list1.pop() # 删除最后一个元素 list1.pop(0) # 删除指定的元素 list1.clear() # 清空列表 # 修改 list1[0] = 'json' # 指定索引修改 # 统计 len(list1) # 列表元素的长度: 3 list1.count('tom') # 数据在列表中出现的次数 # 排序 list1.sort() # 按字母升序排序 list1.sort(reverse=True) # 倒序 list1.reverse() # 按反转列表 print(list1)
Tuple
与list 类似, 不同的是 元组的元素不能修改, 可以保护数据的安全tuple = ('tom', 18, 17.5) print(type(tuple)) # class 'tuple' print(tuple[0]) # tom print(tuple[1]) # 18 # 共2个方法 tuple = ('tom', 18, 17.5, 'tom') print(tuple.index('tom')) # 第一次出现的数据的索引:0 print(tuple.count('tom')) # 出现的次数: 2 print(len(tuple)) # 元素个数为:4
Dictionary
通常用于存储描述一个物体的相关信息dict = {"name":"jack"} # 取值:如果键不存在就会报错 print(dict['name']) # jack # 增加: 不存在时 dict['age'] = 24 # 修改:存在时 dict['name'] = "tom" # 删除:如果键不存在就会报错 dict.pop('name') print(dict) # 在实际开发中,由于字典中每一个键值对保存数据的类型是不同的,所以针对字典的循环遍历需求并不是很多 for k in dict: print("%s:%s" % (k, dict[k])) # 主要方法 clear() get() pop() update() copy() items() popitem() values() fromkeys() keys() setdefault()
list(元组) 与 tuple(列表) 的转换
num_list = [1, 2, 3, 4] print(type(num_list)) # class 'list' # list 转 tuple num_tuple = tuple(num_list) print(type(num_tuple)) # class 'tuple' # tuple 转 list num_list = list(num_tuple) print(type(num_list)) # class 'list'
相关文章推荐
- Python学习笔记———列表(list)、元组(tuple)、字典(dict)
- Python入门(三)——list和tuple,条件判断和循环,dict和set
- Python list,tuple,dict,set区别
- python 中的“集合”(list、tuple、set、dict)
- Python中 list、tuple、dict、set的区别(Python)
- python入门list和tuple,dict和set
- python中str(字符串)、list(列表)、tuple(元组)、dict(字典)相互转化关系及字典键-值遍历
- python list tuple dict set
- 自学python(03)list和tuple,条件判断和循环,dict和set
- Python中的列表(list),元组(Tuple),字典(Dict)和集合(Set)
- python 基本类型list、tuple、dict学习
- Python之List,Tuple,Set,Dict
- python函数传递list,tuple和dict时的复制关系
- Python学习笔记-四类数据存储结构:list、tuple、dict以及set
- python之list、tuple、dict、set对比
- Python学习笔记--表list, 元组tuple, 字典dict
- python 科普:数据类型list、tuple、dict
- Python中内置数据类型list,tuple,dict,set的区别和用法
- Python数据结构 字符串,列表list,元组tuple,字典dict,容器
- 廖雪峰python3.6教程笔记3-Python基础之使用list, tuple, dict和set