一、Python兩個list合併成字典
要將兩個列表合併為字典,可以使用zip函數將兩個列錶轉換為元組,然後使用dict函數將元組轉換為字典。以下是示例代碼:
list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd', 'e'] zip_obj = zip(list1, list2) dict_obj = dict(zip_obj) print(dict_obj)
輸出結果為:
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
二、Python兩個list合併成dataframe
要將兩個列表合併為dataframe,可以使用pandas庫中的DataFrame函數。以下是示例代碼:
import pandas as pd list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd', 'e'] df = pd.DataFrame({'col1': list1, 'col2': list2}) print(df)
輸出結果為:
col1 col2 0 1 a 1 2 b 2 3 c 3 4 d 4 5 e
三、Python兩個list合併成一個list
要將兩個列表合併為一個列表,可以使用extend函數或加法運算符。以下是示例代碼:
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list1.extend(list2) print(list1) list3 = list1 + list2 print(list3)
輸出結果分別為:
[1, 2, 3, 'a', 'b', 'c'] [1, 2, 3, 'a', 'b', 'c', 'a', 'b', 'c']
四、Python兩個list集合合併成一個
要將兩個列表集合合併為一個,可以使用set函數去除重複元素,然後使用union函數合併集合。以下是示例代碼:
set1 = {1, 2, 3} set2 = {3, 4, 5} set3 = set1.union(set2) print(set3)
輸出結果為:
{1, 2, 3, 4, 5}
五、Python兩個字典的合併
要將兩個字典合併,可以使用update函數或運算符。以下是示例代碼:
dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4} dict1.update(dict2) print(dict1) dict3 = {**dict1, **dict2} print(dict3)
輸出結果分別為:
{'a': 1, 'b': 2, 'c': 3, 'd': 4} {'a': 1, 'b': 2, 'c': 3, 'd': 4}
六、Python兩個列表怎麼合併
已經在前面介紹過了,可以使用extend函數或加法運算符將兩個列表合併為一個。以下是示例代碼:
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list1.extend(list2) print(list1) list3 = list1 + list2 print(list3)
輸出結果分別為:
[1, 2, 3, 'a', 'b', 'c'] [1, 2, 3, 'a', 'b', 'c', 'a', 'b', 'c']
七、Python兩個列表合併再排序
要將兩個列表合併再排序,可以使用sorted函數。以下是示例代碼:
list1 = [3, 2, 1] list2 = [6, 5, 4] list3 = list1 + list2 list3 = sorted(list3) print(list3)
輸出結果為:
[1, 2, 3, 4, 5, 6]
八、Python兩個文件合併
要將兩個文件合併,可以先讀取兩個文件內容,然後將內容合併後寫入一個新文件中。以下是示例代碼:
with open('file1.txt') as f1: content1 = f1.read() with open('file2.txt') as f2: content2 = f2.read() with open('file3.txt', 'w') as f3: f3.write(content1 + content2)
此處將file1.txt和file2.txt的內容合併後寫入file3.txt文件中。
九、Python合併兩個列表
已經在前面介紹過了,可以使用extend函數或加法運算符將兩個列表合併為一個。以下是示例代碼:
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list1.extend(list2) print(list1) list3 = list1 + list2 print(list3)
輸出結果分別為:
[1, 2, 3, 'a', 'b', 'c'] [1, 2, 3, 'a', 'b', 'c', 'a', 'b', 'c']
以上就是Python兩個list合併的多種方法,根據實際需求選擇合適的方法即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/188439.html