2020年4月4日python学习笔记——基本数据类型转换
# 本篇总结了一下字符串,列表,字典,元组的连接组合使用和类型的互相转换 # 1.连接两个字符串 # a = "hello " # b = "word" # print(a+b) # 字典的连接 # dict1 = {1: "a", 2: "b"} # dict2 = {3: "c", 4: "d"} # dict1.update(dict2) # print(dict1) # 列表的连接 # list1 = [1, 2, 3,4] # list2 = [4, 5, 6] # list1.extend(list2)#[1, 2, 3, 4, 4, 5, 6] # print(list1) # 元组的连接 # tuple1 = (1, 2) # tuple2 = (3, 4) # tuple3 = tuple2+tuple1 # print(tuple3) # (1, 2, 3, 4) #字典转换为其他类型 字符 列表 元组 # 字典转换为字符串 # dict1 = {1: "a", 2: "b"} # str1 = str(dict1) # print(str1) # print(type(str1)) # 字典转换为列表 # dict1 = {1: "a", 2: "b"} # list1 = list(dict1.keys()) # list2 = list(dict1.values()) # list3 = list(dict1)#--------------直接返回key值 # print(list1) # [1, 2] # print(list2) # ['a', 'b'] # print(list3) # [1,2] # 直接拿到key值 # dict = {"he":"good","live":3} # print(list(dict)) # 字典转换为元组 原理:等同与字典转换为列表 # dict1 = {1: "a", 2: "b"} # tuple1 = tuple(dict1.keys()) # tuple2 = tuple(dict1.values()) # tuple3 = tuple(dict1) # print(tuple1) # (1, 2) # print(tuple2) # ('a', 'b') # print(tuple3) # (1, 2) #列表转换为其他类型 字符串 字典 元组 #列表转换为字符串 # list1 = [1, 2, 3] # str1 = str(list1) # print(str1) # [1, 2, 3] # print(type(str1)) # <class 'str'> # 列表转换为字典 # 1. 2个列表,第一个列表作为key 第二个列表作为vule。 使用dict(zip(列表1,列表2)) # list1 = [1, 2, 3] # list2 = ["a", "b", "c"] # dict1 = dict(zip(list1, list2)) # print(dict1) # {1: 'a', 2: 'b', 3: 'c'} # 2. # list1 = [1, 2, 3] # list2 = ["a", "b", "c"] # dict1 = {} # for i in list1: # dict1[i] = list2[list1.index(i)] # print(dict1) # {1: 'a', 2: 'b', 3: 'c'} # 3 现成的列表对,直接转换成字典模式. # list1 = [[1, 'a'], [2, 'b'], [3, 'c']] # dict1 = dict(list1) # print(dict1) # {1: 'a', 2: 'b', 3: 'c'} # # 列表转换为元组 # list1 = [1, 2, 3] # tuple1 = tuple(list1) # print(tuple1) # (1, 2, 3) #列表转换为其他类型 字符串 字典 列表 # 元组转换为字符串 # tuple1 = (1, 2, 3) # str1 = str(tuple1) # print(str1) # (1, 2, 3) # print(type(str1)) # <class 'tuple'> # 元组转换为字典 # 1. 2个元组,第一个元组作为key 第二个元组作为vule。 使用dict(zip(元组1,元组2)) # tuple1 = (1, 2, 3) # tuple2 = (4, 5, 6) # dict1 = dict(zip(tuple1, tuple2)) # print(dict1) # {1: 4, 2: 5, 3: 6} # 2 # tuple1 = (1, 2, 3) # tuple2 = (4, 5, 6) # dict1 = {} # for i in tuple1: # dict1[i] = tuple2[tuple1.index(i)] # print(dict1) # {1: 4, 2: 5, 3: 6} # 3 现成的元组对,直接转换成字典模式. # tuple1 = (1, 2) # tuple2 = (4, 5) # tuple3 = (tuple1, tuple2) # dict1 = dict(tuple3) # print(dict1) # {1: 2, 4: 5} # 元组转换为列表 # tuple1 = (1, 2) # list1 = list(tuple1) # print(list1) # [1, 2]
posted on 2020-04-04 20:17 坚持是多么伟大的事情 阅读(168) 评论(0) 编辑 收藏 举报