python集合用法实例分析

本文实例讲述了python集合用法。分享给大家供大家参考。具体分析如下:

# sets are unordered collections of unique hashable elements
# python23 tested vegaseat 09mar2005
# python v2.4 has sets built in
import sets
print “list the functions within module ‘sets’:”
for funk in dir(sets):
print funk
# create an empty set
set1 = set([])
# now load the set
for k in range(10):
set1.add(k)
print “\nloaded a set with 0 to 9:”
print set1
set1.add(7)
print “tried to add another 7, but it was already there:”
print set1
# make a list of fruits as you put them into a basket
basket = [‘apple’, ‘orange’, ‘apple’, ‘pear’, ‘orange’, ‘banana’]
print “\nthe original list of fruits:”
print basket
# create a set from the list, removes the duplicates
fruits = sets.set(basket)
print “\nthe set is unique, but the order has changed:”
print fruits
# let’s get rid of some duplicate words
str1 = “senator strom thurmond dressed as as tarzan”
print “\noriginal string:”
print str1
print “a list of the words in the string:”
wrdlist1 = str1.split()
print wrdlist1
# now create a set of unique words
strset = sets.set(wrdlist1)
print “the set of the words in the string:”
print strset
print “convert set back to string (order has changed!):”
print ” “.join(strset)
print
# comparing two sets, bear with me …
colorset1 = sets.set([‘red’,’green’,’blue’,’black’,’orange’,’white’])
colorset2 = sets.set([‘black’,’maroon’,’grey’,’blue’])
print “colorset1 =”, colorset1
print “colorset2 =”, colorset2
# same as (colorset1 – colorset2)
colorset3 = colorset1.difference(colorset2)
print “\nthese are the colors in colorset1 that are not in colorset2:”
print colorset3
# same as (colorset1 | colorset2)
colorset4 = colorset1.union(colorset2)
print “\nthese are the colors appearing in both sets:”
print colorset4
# same as (colorset1 ^ colorset2)
colorset5 = colorset1.symmetric_difference(colorset2)
print “\nthese are the colors in colorset1 or in colorset2, but not both:”
print colorset5
# same as (colorset1 & colorset2)
colorset6 = colorset1.intersection(colorset2)
print “\nthese are the colors common to colorset1 and colorset2:”
print colorset6

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类

发表评论