Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
सेट्स
सेट्स सूची हैं जिनमें कोई डुप्लिकेट प्रविष्टियाँ नहीं होती हैं। मान लीजिए आप एक अनुच्छेद में उपयोग किए गए शब्दों की सूची संग्रह करना चाहते हैं:
print(set("my name is Eric and Eric is my name".split()))
यह "my", "name", "is", "Eric", और अंत में "and" से युक्त एक सूची प्रिंट करेगा। चूंकि बाक़ी वाक्य में ऐसे शब्द हैं जो पहले से ही सेट में हैं, उन्हें दो बार शामिल नहीं किया जाता है।
सेट्स Python में एक शक्तिशाली उपकरण हैं क्योंकि इनमें अन्य सेट्स के बीच अंतर और इंटरेक्शन की गणना करने की क्षमता होती है। उदाहरण के लिए, मान लीजिए आपके पास इवेंट A और B में प्रतिभागियों की सूची है:
a = set(["Jake", "John", "Eric"])
print(a)
b = set(["John", "Jill"])
print(b)
यह जानने के लिए कि कौन से सदस्यों ने दोनों इवेंट्स में भाग लिया, आप "intersection" विधि का उपयोग कर सकते हैं:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.intersection(b))
print(b.intersection(a))
यह जानने के लिए कि कौन से सदस्य केवल एक इवेंट में शामिल हुए, "symmetric_difference" विधि का उपयोग करें:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.symmetric_difference(b))
print(b.symmetric_difference(a))
यह जानने के लिए कि कौन से सदस्य केवल एक इवेंट में शामिल हुए और दूसरे में नहीं, "difference" विधि का उपयोग करें:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.difference(b))
print(b.difference(a))
सभी प्रतिभागियों की सूची प्राप्त करने के लिए, "union" विधि का उपयोग करें:
a = set(["Jake", "John", "Eric"])
b = set(["John", "Jill"])
print(a.union(b))
Exercise-------- नीचे दिए गए अभ्यास में, दी गई सूचियों का उपयोग करके इवेंट A के उन सभी प्रतिभागियों के सेट को प्रिंट करें जिन्होंने इवेंट B में भाग नहीं लिया।
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
a = ["Jake", "John", "Eric"]
b = ["John", "Jill"]
A = set(a)
B = set(b)
print(A.difference(B))
test_output_contains("['Jake', 'Eric']")
success_msg("Nice work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!