您好,登錄后才能下訂單哦!
本篇內容介紹了“Python中基本類型的連接組合和互相轉換的方式”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
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中基本類型的連接組合和互相轉換的方式”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。