Python 字典中兩個不等長列表的壓縮


介紹

在 Python 中,列表和字典是最常用的資料收集和處理方法之一。有很多與列表和字典相關的操作通常用於以所需的形式獲取資料。有時我們可能還需要壓縮兩個不同的列表,並將壓縮後的列表以字典的形式獲取。

在本文中,我們將討論兩個不等長列表的壓縮操作,並將輸出作為字典。本文將幫助讀者瞭解列表壓縮操作背後的原理,並從中生成字典。

所以讓我們開始討論壓縮兩個不等長列表的含義。

壓縮兩個不等長列表

在 Python 中,在收集和處理資料時,壓縮是最常見的操作之一,它涉及以鍵值對的方式新增兩個列表。簡單來說,就是對列表中的值或元素進行排序或表示,使其在輸出結果中看起來像鍵值對。

此操作是最常見的一種,因為有時我們可能需要一個列表或字典,它是兩個不同列表的組合。我們可以有兩個不同大小或長度的列表,我們可以將它們壓縮並以字典形式獲取輸出,以便更容易、更有效地處理資料。

有很多方法可以做到這一點。讓我們討論其中的一些。

方法 1:使用 Itertools + Cycle

我們可以使用 itertools 庫並匯入 cycle 以壓縮兩個列表並將字典作為輸出。

# Itertools + Cycle Method 


# Import the cycle from itertools
from itertools import cycle

# define two lists
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = [1, 2, 3, 4]

# zip the lists and pass them into the dictionary form
res = dict(zip(list1, cycle(list2)))

# print the final results
print("Final Output Dictionary : ", str(res))

正如我們在上面的程式碼中看到的,我們首先從 itertools 中匯入了 cycle,然後定義了兩個不同大小的列表。

然後使用 itertools 中的 cycle 來壓縮兩個不等長列表,並將輸出表示為字典形式。

輸出

以下程式碼的輸出將是

Final Output Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

方法 2:使用 deque

與 itertools 中的 cycle 相同,我們可以使用 collections 中的 deque。透過匯入 deque,我們可以壓縮兩個列表並獲取字典。

# using deque for zipping lists

from collections import deque

# define two list that are to be zipped 
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = deque([1, 2, 3, 4])

# zip teh lists using deque
result = {}
for letter in ini_lis1:
  number = ini_lis2.popleft()
  result[letter] = number
  ini_lis2.append(number)


# print the final results
print("Output Dict : ", str(result))

正如我們在上面的程式碼中看到的,在從 collections 匯入 deque 後,定義了兩個不同大小的列表。

然後使用 for 迴圈使用 append 來壓縮兩個列表。最終結果將以字典的形式打印出來。

輸出

此程式碼的輸出將是

Output Dict : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

方法 3:使用 Default 類

default 類也可用於壓縮兩個不同大小的列表並將字典作為輸出。

# using default class method

# import default dict from collections
from collections import defaultdict

# define two lists
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# use default dict
result = defaultdict(int)

# add values to the keys respectively
for i in range(len(ini_lis1)):
	result[ini_lis1[i]] += ini_lis2[i % len(ini_lis2)]

# print the final results
print("Output Dict: ", str(dict(result)))

正如我們在上面的程式碼中看到的,在匯入 default 類後定義了兩個列表,並使用 for 迴圈將值新增到相應的鍵中。

這裡需要注意的是,如果資料中不存在鍵,它將返回預設值。這裡我們取預設值為 0。

輸出

以下程式碼的輸出將是

Output Dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

方法 4:使用 Zip() + Dict()

這是壓縮兩個不同列表並將輸出作為字典的最簡單方法之一。

# using zip + dict method
# define two lists that are to be zipped
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# use zip()
result = dict(zip(ini_lis1, ini_lis2 *
        ((len(ini_lis1) + len(ini_lis2) - 1) // len(ini_lis2))))

# print the final results
print("Output Dict: ", str(result))

這裡,正如我們在上面的程式碼中看到的,我們首先定義兩個不同的列表,然後在定義結果時,將語法或程式碼傳遞給 dict(),它將以字典資料格式返回輸出。為了在這裡壓縮兩個列表,使用了 zip 關鍵字,它附加了兩個不同列表的值。

輸出

以下程式碼的輸出將是

Output Dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

方法 5:使用 Itertools() + enumerate()

在這種方法中,我們將使用 Itertools 庫,並在壓縮兩個列表的過程中使用 enumerate。

# using itertools + enumerate
# Import itertools
from itertools import cycle

# define two lists
ini_lis1 = ['a', 'b', 'c', 'd', 'e']
ini_lis2 = [1, 2, 3, 4]

# zip the two lists using for loop and enumerate
result = {v: ini_lis2[i % len(ini_lis2)]
    for i, v in enumerate(ini_lis1)}

# print the final results
print("Output Dict : ", str(result))

正如我們在上面的程式碼中看到的,我們首先從 itertools 中匯入 cycle,然後定義兩個不同大小的列表。然後使用 for 迴圈和 enumerate 函式,我們將兩個不同列表的值或元素加起來(壓縮),然後這些值以字典的形式表示。

輸出

以下程式碼的輸出將是

Output Dict : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}

結論

在本文中,我們討論了 Python 中六種不同方法壓縮兩個不同大小列表的操作,並提供了程式碼示例和解釋。本文將幫助讀者在需要時執行類似的操作。

更新於: 2023-07-27

965 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告