小編給大家分享一下Python基本類型的連接組合和互相轉(zhuǎn)換方式有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
創(chuàng)新互聯(lián)2013年開創(chuàng)至今,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項目網(wǎng)站設(shè)計制作、網(wǎng)站建設(shè)網(wǎng)站策劃,項目實(shí)施與項目整合能力。我們以讓每一個夢想脫穎而出為使命,1280元田家庵做網(wǎng)站,已為上家服務(wù),為田家庵各地企業(yè)和個人服務(wù),聯(lián)系電話:18982081108字符串,列表,字典,元組的連接組合使用和類型的互相轉(zhuǎn)換小例子,尤其列表中的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.字典轉(zhuǎn)換為字符串
dict1 = {1: "a", 2: "b"} str1 = str(dict1) print(str1) # {1: 'a', 2: 'b'} print(type(str1)) #
6.字典轉(zhuǎn)換為列表
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.字典轉(zhuǎn)換為元組
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.列表轉(zhuǎn)換為字符串
list1 = [1, 2, 3] str1 = str(list1) print(str1) # [1, 2, 3] print(type(str1)) #
9.列表轉(zhuǎn)換為字典
# 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.列表轉(zhuǎn)換為元組
list1 = [1, 2, 3] tuple1 = tuple(list1) print(tuple1) # (1, 2, 3)
11.元組轉(zhuǎn)換為字符串
tuple1 = (1, 2, 3) str1 = tuple(tuple1) print(str1) # (1, 2, 3) print(type(str1)) #
12.元組轉(zhuǎn)換為字典
# 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.元組轉(zhuǎn)換為列表
tuple1 = (1, 2) list1 = list(tuple1) print(list1) # [1, 2]
以上是“Python基本類型的連接組合和互相轉(zhuǎn)換方式有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!