Python基本类型的连接组合和互相转换方式(13种)

yipeiwu_com6年前Python基础

本篇总结了一下字符串,列表,字典,元组的连接组合使用和类型的互相转换小例子,尤其列表中的extend()方法和字典中的

update方法非常的常用。

1.连接两个字符串

a = "hello " 
b = "world" 
a += b 
print(a) # hello world

2.字典的连接

dict1 = {1: "a", 2: "b"} 
dict2 = {3: "c", 4: "d"} 
dict1.update(dict2) 
print(dict1) # {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

3.列表的连接

list1 = [1, 2, 3] 
list2 = [4, 5, 6] 
list1.extend(list2) # [1, 2, 3, 4, 5, 6] 
print(list1)

4.元组的连接

tuple1 = (1, 2) 
tuple2 = (3, 4) 
tuple1 += tuple2 
print(tuple1) # (1, 2, 3, 4)

5.字典转换为字符串

dict1 = {1: "a", 2: "b"} 
str1 = str(dict1) 
print(str1) # {1: 'a', 2: 'b'} 
print(type(str1)) # <class 'str'>

6.字典转换为列表

dict1 = {1: "a", 2: "b"} 
list1 = list(dict1.keys()) 
list2 = list(dict1.values()) 
list3 = list(dict1) 
print(list1) # [1, 2] 
print(list2) # ['a', 'b'] 
print(list3) # [1,2]

7.字典转换为元组

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) 

8.列表转换为字符串

list1 = [1, 2, 3] 
str1 = str(list1) 
print(str1) # [1, 2, 3] 
print(type(str1)) # <class 'str'>

9.列表转换为字典

# 1. 
list1 = [1, 2, 3] 
list2 = ["a", "b", "c"] 
dict1 = dict(zip(list1, list2)) 
print(dict1) # {1: 'a', 2: 'b', 3: 'c'} 
# 2. 
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'}

10.列表转换为元组

list1 = [1, 2, 3] 
tuple1 = tuple(list1) 
print(tuple1) # (1, 2, 3)

11.元组转换为字符串

tuple1 = (1, 2, 3) 
str1 = tuple(tuple1) 
print(str1) # (1, 2, 3) 
print(type(str1)) # <class 'tuple'>

12.元组转换为字典

# 1. 
tuple1 = (1, 2, 3) 
tuple2 = (4, 5, 6) 
dict1 = dict(zip(tuple1, tuple2)) 
print(dict1) # {1: 4, 2: 5, 3: 6} 
# 2 
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}

13.元组转换为列表

tuple1 = (1, 2) 
list1 = list(tuple1) 
print(list1) # [1, 2]

总结

以上所述是小编给大家介绍的Python基本类型的连接组合和互相转换方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python寻找两个有序数组的中位数实例详解

Python寻找两个有序数组的中位数实例详解

Python寻找两个有序数组的中位数 审题: 1.找出意味着这是一个查找算法题 2.算法复杂度log级别,就是提示你是二分查找 3.二分查找实现一般为递归  (1)递归包括递...

Python面向对象程序设计中类的定义、实例化、封装及私有变量/方法详解

本文实例讲述了Python面向对象程序设计中类的定义、实例化、封装及私有变量/方法。分享给大家供大家参考,具体如下: 1. 定义类 python中定义一个类的格式如下: class...

详解使用python的logging模块在stdout输出的两种方法

详解使用python的logging模块在stdout输出 前言:   使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志...

Python3.5内置模块之os模块、sys模块、shutil模块用法实例分析

Python3.5内置模块之os模块、sys模块、shutil模块用法实例分析

本文实例讲述了Python3.5内置模块之os模块、sys模块、shutil模块用法。分享给大家供大家参考,具体如下: 1、os模块:提供对操作系统进行调用的接口 #!/usr/b...

解决PySide+Python子线程更新UI线程的问题

在我开发的系统,需要子线程去运行,然后把运行的结果发给UI线程,让UI线程知道运行的进度。 首先创建线程很简单 def newThread(self): d = Data() p...