將兩個長度不相等的列表壓縮成一個Python字典

WBOY
發布: 2023-08-19 11:29:06
轉載
1149 人瀏覽過

將兩個長度不相等的列表壓縮成一個Python字典

介紹

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

在本文中,我們將討論兩個長度不相等的列表的壓縮操作,並將輸出結果作為字典。本文將幫助讀者了解清單的壓縮操作,並從中產生一個字典。

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

壓縮兩個長度不相等的列表

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

這個運算是最常見的之一,因為有時我們可能需要一個由兩個不同清單組合而成的清單或字典。我們可以有兩個不同大小或長度的列表,然後將它們合併並以字典形式輸出,以便更輕鬆、有效率地處理資料。

有很多方法可以達到相同的效果。讓我們討論其中一些方法。

方法1:使用Itertools Cycle

We can use the itertools library and can import the cycle in order to zip the two lists and get the dictionary as an output.

# 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中的循環函數將兩個長度不相等的列表進行壓縮,然後將輸出表示為字典形式。

輸出

以下程式碼的輸出結果將會是:

Final Output Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}
登入後複製

Method 2: Use deque

和itertools中的迴圈一樣,我們可以使用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}
登入後複製
登入後複製

方法三:使用預設類別

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

# 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)))
登入後複製

正如我們可以在上面的程式碼中看到,在導入預設類別之後定義了兩個列表,並使用for循環將值添加到相應的鍵中。

請注意,如果資料中沒有該鍵,則它將傳回預設值。在這裡,我們使用預設值0。

輸出

以下程式碼的輸出結果將會是:

Output Dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 1}
登入後複製
登入後複製

方法四:使用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中兩個不同大小清單的壓縮操作,並提供了程式碼範例和說明。本文將幫助讀者在需要時執行類似的操作。 ###

以上是將兩個長度不相等的列表壓縮成一個Python字典的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!