当前位置: 移动技术网 > IT编程>开发语言>C/C++ > python集合使用范例的代码

python集合使用范例的代码

2018年12月13日  | 移动技术网IT编程  | 我要评论

网易交友中心,宁河,ca197

在代码过程中中,将代码过程中比较好的代码段珍藏起来,如下的代码是关于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

  





 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网