এই টিউটোরিয়ালে, আমরা একটি প্রোগ্রাম লিখব যা টাপলের লিস্ট থেকে একই দ্বিতীয় উপাদানযুক্ত সব টাপল গ্রুপ করবে। ভালো বুঝার জন্য একটি উদাহরণ দেখা যাক।
ইনপুট
[('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
আউটপুট
{'tutorialspoints': [('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 ব্যবহার করে সমাধান করা যাক।
উদাহরণ
# collections থেকে defaultdict ইম্পোর্ট
from collections import defaultdict
# টাপলসহ লিস্ট ইনিশিয়ালাইজ
tuples = [('Python', 'tutorialspoints'), ('Management', 'other'), ('Django', 'tutorialspoints'), ('React', 'tutorialspoints'), ('Social', 'other'), ('Business', 'other')]
# defaultdict সহ খালি ডিক্ট
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')]}
উপসংহার
আপনি ভিন্ন ভিন্ন উপায়ে সমস্যা সমাধান করতে পারেন। এখানে আমরা দুটি উপায় দেখেছি। যদি টিউটোরিয়ালের বিষয়ে কোনো প্রশ্ন থাকে, তবে কমেন্ট সেকশনে জানান।