本篇总结了一下字符串,列表,字典,元组的连接组合使用和类型的互相转换小例子,尤其列表中的extend()方法和字典中的
10年积累的成都网站设计、成都网站制作、外贸网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站设计后付款的网站建设流程,更有密云免费网站建设让你可以放心的选择与我们合作。
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)) #
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)) #
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)) #
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中基本类型的连接组合和互相转换13种方式
文章转载:http://www.mswzjz.com/qtweb/news24/169374.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联