Python’da Küme Kullanımı

Aralık 14th, 2011 § Yorum yok

from sets import Set
students = Set(['Joe', 'Jane', 'Mary', 'Pete'])
programmers = Set(['Caroline', 'Tom', 'John', 'Pete'])
designers = Set(['Paul', 'Mary', 'Susan', 'Pete'])

print "These are the students:"
for student in students:
   print student,
print "!"

print "There are", len(students), "students."
print

people = students | programmers | designers           # union
print "All people:", people
print

student_designers = students & designers              # intersection
print "Students who also design:", student_designers
print

non_design_students = students - designers            # difference
print "Students who do not design:", non_design_students

Küme İşlemleri

len(s)

cardinality of set s

x in s

test x for membership in s

x not in s

test x for non-membership ins

s.issubset(t)

test whether every element in
s is in t

s.issuperset(t)

test whether every element in
t is in s

s | t

Union: new set with elements from both
s and t

s & t

Intersection: new set with elements common to
s and t

s - t

Difference: new set with elements in s
but not in t

s ^ t

Symmetric difference: new set with elements in either
s or t but not both

s.copy()

new set with a shallow copy of s

s.add(x)

add element x to set s

s.discard(x)

remove element x from set s

s.clear()

remove all elements from set s

s == t

test whether sets s and t are equal

s != t

test whether sets s and t are not equal

Küme Kopyalamak ve Karşılaştırmak

Kümeyi kopyalamak için copy() kullanılmalıdır.

from sets import Set
odd = Set([1,3,5])
even = Set([2,4,6])
copy1 = odd
copy2 = odd.copy()

>>> print "Are copy1 and odd the same?", copy1 is odd
Are copy1 and odd the same? True
>>> print "Are copy1 and odd equal?", copy1 == odd
Are copy1 and odd equal? True
>>> print "Are copy2 and odd the same?", copy2 is odd
Are copy2 and odd the same? False
>>> print "Are copy2 and odd equal?",copy2 == odd
Are copy2 and odd equal? True


odd.add(7)
>>> print odd
Set([1, 3, 5, 7])
>>> print "copy1:", copy1
copy1: Set([1, 3, 5, 7])
>>> print "copy2:", copy2
copy2: Set([1, 3, 5])


Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

Ne yapıyorum ben!?

Python’da Küme Kullanımı başlıklı yazıyı okuyorsun.

Üst Veri