इस ट्यूटोरियल में, हम एक प्रोग्राम लिखने जा रहे हैं जो सभी टुपल्स को एक सूची से समूहित करता है जिसमें दूसरे तत्व के समान तत्व होता है। आइए इसे स्पष्ट रूप से समझने के लिए एक उदाहरण देखें।
इनपुट
[('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 . का उपयोग करके उपरोक्त कार्यक्रम में स्थिति . आइए इसे डिफॉल्टडिक्ट . का उपयोग करके हल करें ।
उदाहरण
# 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')]} निष्कर्ष
आप इसे अपनी पसंद के अनुसार अलग-अलग तरीकों से हल कर सकते हैं। हमने यहां दो तरीके देखे हैं। यदि आपको ट्यूटोरियल में कोई संदेह है, तो उनका टिप्पणी अनुभाग में उल्लेख करें।