Python 列表中元組分組,按第二個元組值匹配
在本教程中,我們將編寫一個程式,對列表中所有具有相同第二個元素的元組進行分組。讓我們看一個例子來更清晰地理解它。
輸入
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React',
'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]輸出
{'tutorialspoint': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')],
'other’: [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}我們必須對列表中的元組進行分組。讓我們看看解決這個問題的步驟。
- 用所需的元組初始化一個列表。
- 建立一個空字典。
- 遍歷元組列表。
- 檢查元組的第二個元素是否已存在於字典中。
- 如果已存在,則將當前元組追加到其列表中。
- 否則,用包含當前元組的列表初始化鍵。
- 最後,您將獲得一個具有所需修改的字典。
示例
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict
result = {}
# iterating over the list of tuples
for tup in tuples:
# checking the tuple element in the dict
if tup[1] in result:
# add the current tuple to dict
result[tup[1]].append(tup)
else:
# initiate the key with list
result[tup[1]] = [tup]
# priting the result
print(result)輸出
如果您執行上面的程式碼,則會得到以下結果。
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}我們使用**defaultdict**跳過了上面程式中的**if**條件。讓我們使用**defaultdict**來解決它。
示例
# importing defaultdict from collections
from collections import defaultdict
# initializing the list with tuples
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 't
ialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'othe
r')]
# empty dict with defaultdict
result = defaultdict(list)
# iterating over the list of tuples
for tup in tuples:
result[tup[1]].append(tup)
# priting the result
print(dict(result))輸出
如果您執行上面的程式碼,則會得到以下結果。
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints
('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other
'), ('Business', 'other')]}結論
您可以根據自己的喜好以不同的方式解決它。我們在這裡看到了兩種方法。如果您對本教程有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP