इस ट्यूटोरियल में, हम एक प्रोग्राम लिखने जा रहे हैं जो सूची के उन सभी टपल्स को समूहित करता है जिनमें दूसरे तत्व के रूप में समान तत्व होता है। आइए इसे स्पष्ट रूप से समझने के लिए एक उदाहरण देखें।
इनपुट
[('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')]}
हमें सूची से टपल्स को समूहित करना है। समस्या को हल करने के चरण देखते हैं।
- आवश्यक टपल्स के साथ सूची आरंभ करें।
- एक खाली डिक्शनरी बनाएं।
- टपल्स की सूची पर पुनरावृति करें।
- जांचें कि टपल का दूसरा तत्व पहले से ही डिक्शनरी में मौजूद है या नहीं।
- यदि पहले से मौजूद है, तो वर्तमान टपल को उसकी सूची में जोड़ें।
- अन्यथा वर्तमान टपल वाली सूची के साथ कुंजी आरंभ करें।
- अंत में, आपको आवश्यक संशोधनों के साथ एक डिक्शनरी मिलेगी।
उदाहरण
# टपल्स के साथ सूची आरंभ करना
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
# खाली डिक्ट
result = {}
# टपल्स की सूची पर पुनरावृति
for tup in tuples:
# डिक्ट में टपल तत्व की जांच
if tup[1] in result:
# वर्तमान टपल को डिक्ट में जोड़ें
result[tup[1]].append(tup)
else:
# सूची के साथ कुंजी आरंभ करें
result[tup[1]] = [tup]
# परिणाम प्रिंट करना
print(result)
आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न परिणाम मिलेगा।
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
हम ऊपर दिए गए प्रोग्राम में if शर्त को defaultdict का उपयोग करके छोड़ सकते हैं। आइए इसे defaultdict का उपयोग करके हल करें।
उदाहरण
# कलेक्शन से डिफॉल्टडिक्ट आयात करना
from collections import defaultdict
# टपल्स के साथ सूची आरंभ करना
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
# डिफॉल्टडिक्ट के साथ खाली डिक्ट
result = defaultdict(list)
# टपल्स की सूची पर पुनरावृति
for tup in tuples:
result[tup[1]].append(tup)
# परिणाम प्रिंट करना
print(dict(result))
आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न परिणाम मिलेगा।
{'tutorialspoints': [('Python', 'tutorialspoints'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints')], 'other': [('Management', 'other'), ('Social', 'other'), ('Business', 'other')]}
निष्कर्ष
आप इस समस्या को अपनी पसंद के अलग-अलग तरीकों से हल कर सकते हैं। हमने यहां दो तरीके देखे हैं। यदि ट्यूटोरियल में आपके कोई संदेह हैं, तो उन्हें टिप्पणी अनुभाग में उल्लेख करें।