• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python集合使用范例

python 水墨上仙 2943次浏览

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集合使用范例
喜欢 (0)
加载中……