python集合用法实例分析

yipeiwu_com5年前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程序设计有所帮助。

相关文章

PyCharm安装Markdown插件的两种方法

PyCharm安装Markdown插件的两种方法

Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式。 从github下载的代码一般都会带有README.md文件,该文件是...

python开发之for循环操作实例详解

本文实例讲述了python开发之for循环操作。分享给大家供大家参考,具体如下: 下面是我做的一些学习记录供大家参考: #基本的for循环语句 test_list = [2,"Jon...

python openvc 裁剪、剪切图片 提取图片的行和列

python openvc 裁剪、剪切图片 提取图片的行和列

python openvc 裁剪图片 下面是4个坐标代码: import cv2 #裁剪图片路径input_path,四个裁剪坐标为:y1,y2,x1,x2,保存剪裁后的图片路径ou...

python先序遍历二叉树问题

python先序遍历二叉树问题

问题 如何遍历一个二叉树 遍历二叉树就是访问二叉树的每一个节点 二叉树父结点下先左访问,先序遍历(根左右) 例如:遍历以下的二叉树 遍历结果:ABDECF Python代码示例...

Python补齐字符串长度的实例

如下所示: ljust(len,str)字符向左对齐,用str补齐长度 rjust(len,str)字符向右对齐,用str补齐长度 rjust(len,str)字符中间对齐,用s...