python之路:day3

内容

  • 变量的创建过程
  • 身份运算和None
  • 数据类型

一、 变量创建过程                                        

首先,当我们定义了一个变量name = ‘oldboy’的时候,在内存中其实是做了这样一件事:

程序开辟了一块内存空间,将‘oldboy’存储进去,再让变量名name指向‘oldboy’所在的内存地址。如下图所示:

我们可以通过id()方法查看这个变量在内存中的地址

1 >>> name = "oldboy"
2 >>> id(name)
3 4317182304

变量的修改

一般我们认为修改一个变量就是用新值把旧值覆盖掉, 可python是这样实现的么?

1 >>> name = "oldboy"
2 >>> id(name)
3 4317182304
4 >>>
5 >>> name = "alex"
6 >>> id(name) # 如果只是在原有地址上修改,那么修改后内存地址不应该变化呀。
7 4317182360

实际的原理什么样的呢? 程序先申请了一块内存空间来存储‘oldboy’,让name变量名指向这块内存空间

执行到name=‘alex’之后又申请了另一块内存空间来存储‘alex’,并让原本指向‘oldboy’内存的链接断开,让name再指向‘alex’。

       

变量的指向关系

提问:下面这段代码为何出现这样的现象?

1 >>> name1 = 'oldboy'
2 >>> name2 = name1 # 把name1赋值给name2,这样name2的值也是oldboy了
3 >>> print(name1,name2)
4 oldboy oldboy
5 >>>
6 >>> name1 = 'alex'
7 >>> print(name1,name2) #改了name1后,name2为何没跟着改?
8 alex oldboy

要想知道上面问题的结果是为什么,首先要了解在内存中两个变量的存储情况



从上面的示意图中我们可以知道,当执行name2=name1这句话的时候,事实上是让name2指向了‘oldboy’所在的内存地址。

修改name1的值,相当于断开了name1到‘oldboy’的链接,重新建立name1和‘alex’之间的链接。在这个过程中,始终没有影响到name2和‘oldboy‘之间的关系,因此name2还是‘oldboy’,而name1变成了‘alex’。

二、身份运算和None                                       

python 中有很多种数据类型, 查看一个数据的类型的方法是type().

>>> name="克里斯"
>>> age = 29
>>>
>>> name
'克里斯'
>>>
>>> type(name),type(age)
(<class 'str'="">, <class 'int'="">)

判断一个数据类型是不是str, or int等,可以用身份运算符is

>>> type(name) is str
True
>>>
>>> type(name) is not int
True

空值None

代表什么都没有的意思,一般用在哪呢? 比如玩游戏,你要初始化一个女朋友, 需要填上姓名、年龄、身高、体重等信息, 这些信息是让玩家填的,在填之前,你要先把变量定义好,那就得存个值 ,这个值用0,1来占位不合适 ,用True,False也不合适 ,用None最合适

>>> name=None
>>> age=None
>>> height=None
>>> weight=None
>>>
>>> name,age,height,weight
(None, None, None, None)
>>>

此时可用is 运算符来判断变量是不是None

1 >>> if name is None:
2 ... print("你的女朋友还没起名字呢.")
3 ...
4 你的女朋友还没起名字呢.

其实用==判断也行,但是不符合开发规范

>>> name == None
True

三元运算                                                   

显的很NB的代码写法。

1 name = "Eva"
2 sex = None
3 # 普通写法
4 if name == "Eva":
5 sex = "Female"
6 else:
7 sex = "Male"
8 # 用三元运算来写
9 sex = "Female" if name == "Eva" else "Male"

三、数据类型                                          

  • 列表

定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素

再回顾下列表的特点:

1.可存放多个值

2.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

3.可修改指定索引位置对应的值,可变

  列表增加操作

  • 追加,数据会追加到尾部
    1 >>> names
    2 ['alex', 'jack']
    3 >>> names.append("rain")
    4 >>> names.append("eva")
    5 >>>
    6 >>> names
    7 ['alex', 'jack', 'rain', 'eva']

 

  • 插入,可插入任何位置
    1 >>> names.insert(2,"黑姑娘")
    2 >>> names
    3 ['alex', 'jack', '黑姑娘', 'rain', 'eva']
    4 >>>

 

  • 合并,可以把另一外列表的值合并进来
    1 >>> n2 = ["狗蛋","绿毛","鸡头"]
    2 >>> names
    3 ['alex', 'jack', '黑姑娘', 'rain', 'eva']
    4 >>> names.extend(n2)
    5 >>> names
    6 ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']

 

  • 列表嵌套
    >>> names.insert(2,[1,2,3])
    >>> names
    ['alex', 'jack', [1, 2, 3], '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']
    >>> names[2][1]
    2

 

           删除操作

  • del 直接删
    1 >>> names
    2 ['alex', 'jack', [1, 2, 3], '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']
    3 >>> del names[2]
    4 >>> names
    5 ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']
  • pop 删
    1 >>> names
    2 ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛', '鸡头']
    3 >>> names.pop() #默认删除最后一个元素并返回被删除的值
    4 '鸡头'
    5 >>> names
    6 ['alex', 'jack', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛']
    7 >>> help(names.pop)
    8 >>> names.pop(1) #删除指定元素
    9 'jack'

 

  • clear 清空
    1 >>> n2
    2 ['狗蛋', '绿毛', '鸡头']
    3 >>> n2.clear()
    4 >>> n2
    5 []

 

       修改操作

>>> names
['alex', '黑姑娘', 'rain', 'eva', '狗蛋', '绿毛']
>>> names[0] = "金角大王"
>>> names[-1] = "银角大王"
>>> names
['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王']

 

      查操作

1 >>> names
2 ['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王', 'eva']
3 >>>
4 >>> names.index("eva") #返回从左开始匹配到的第一个eva的索引
5 3
6 >>> names.count("eva") #返回eva的个数
7 2

 

     切片

切片就像切面包,可以同时取出元素的多个值

  

1 names[start:end]
2 >>> names
3 ['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王', 'eva']
4 >>> names[1:4] #不包含下标4的元素
5 ['黑姑娘', 'rain', 'eva']

*切片的特性是顾头不顾尾,即start的元素会被包含,end-1是实际取出来的值

倒着切

1 >>> names[-5:-1]
2 ['rain', 'eva', '狗蛋', '银角大王']

但其实我想要的是后5个,只打印了4个,’eva’这个值没出来,为什么,因为上面提到的顾头不顾尾

可是想把后5个全取出来如何做呢?

1 >>> names[-5:]
2 ['rain', 'eva', '狗蛋', '银角大王', 'eva']

如果取前几个值 ,一样可以把:号左边的省掉

>>> names
['金角大王', '黑姑娘', 'rain', 'eva', '狗蛋', '银角大王', 'eva']
>>> names[0:3]
['金角大王', '黑姑娘', 'rain']
>>> names[:3] #跟上面一样的效果
['金角大王', '黑姑娘', 'rain']

步长, 允许跳着取值

 1 names[start:end:step] #step 默认是1
 2 >>> a
 3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 4 >>> a[0:7:2] #设置步长为2
 5 [0, 2, 4, 6]
 6 >>> a
 7 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 8 >>>
 9 >>> a[::3] #按步长3打印列表,第1个:是省略掉的start:end
10 [0, 3, 6, 9]

列表反转

1 >>> a[::-1] #通过把步长设置成负值,可达到列表返转的效果
2 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 
3 >>> a[::-2]
4 [9, 7, 5, 3, 1]

 

排序&反转

  排序

1 >>> a = [83,4,2,4,6,19,33,21]
2 >>> a.sort()
3 >>> a
4 [2, 4, 4, 6, 19, 21, 33, 83]

 

下面的排序结果为何如何解释?

1 >>> names=['金角大王', 'rain', '@', '黑姑娘', '狗蛋', "4","#",'银角大王', 'eva']
2 >>> names.sort()
3 >>> names
4 ['#', '4', '@', 'eva', 'rain', '狗蛋', '金角大王', '银角大王', '黑姑娘']

 

答案全在这张表上,虽然后面我们会讲,但现在先知道,排序的优化级规则是按这张表来的

  反转

1 >>> names
2 ['#', '4', '@', 'eva', 'rain', '狗蛋', '金角大王', '银角大王', '黑姑娘']
3 >>> names.reverse()
4 >>> names
5 ['黑姑娘', '银角大王', '金角大王', '狗蛋', 'rain', 'eva', '@', '4', '#']

 

   循环列表

>>> for i in names:
... print(i)
...
黑姑娘
银角大王
金角大王
狗蛋
rain
eva
@
4
#

编程练习-购物车程序开发

根据以下数据结构:
1 goods = [
2 {"name": "电脑", "price": 1999},
3 {"name": "鼠标", "price": 10},
4 {"name": "游艇", "price": 20},
5 {"name": "美女", "price": 998},
6 ......
7 ]
实现功能要求:

1、启动程序后,让用户输入工资,然后进入循环,打印商品列表和编号

2、允许用户根据商品编号选择商品

3、用户选择商品后,检测余额是否够,够就直接扣款,并加入购物车, 不够就提醒余额不足

4、可随时退出,退出时,打印已购买商品和余额

元组

有些时候我们的列表数据不想被人修改时怎么办? 就可以用元组存放,元组又被称为只读列表,不能修改。

定义:与列表类似,只不过[]改成()

特性:

  1.可存放多个值

  2.不可变

  3.
按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

创建

1 ages = (11, 22, 33, 44, 55)
2 #
3 ages = tuple((11, 22, 33, 44, 55))

常用操作

 1 #索引
 2 >>> ages = (11, 22, 33, 44, 55)
 3 >>> ages[0]
 4 11
 5 >>> ages[3]
 6 44
 7 >>> ages[-1]
 8 55
 9 #切片:同list  
10 #循环
11 >>> for age in ages:
12 print(age)
13 11
14 22
15 33
16 44
17 55
18 #长度
19 >>> len(ages)
20 5
21 #包含
22 >>> 11 in ages
23 True
24 >>> 66 in ages
25 False
26 >>> 11 not in ages
27 False

注意:元组本身不可变,如果元组中还包含其他可变元素,这些可变元素可以改变

1 >>> data
2 (99, 88, 77, ['Alex', 'Jack'], 33)
3 >>> data[3][0] = '金角大王'
4 >>> data
5 (99, 88, 77, ['金角大王', 'Jack'], 33)

为啥呢? 因为元组只是存每个元素的内存地址,上面[‘金角大王’, ‘Jack’]这个列表本身的内存地址存在元组里确实不可变,但是这个列表包含的元素的内存地址是存在另外一块空间里的,是可变的。

字符串

定义

字符串是一个有序的字符的集合,用于存储和表示基本的文本信息,’ ‘或’’ ‘’或’’’ ‘’’中间包含的内容称之为字符串

创建:

  1. s = 'Hello,Eva!How are you?'

特性:

 

    1. 按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序

 

 

    1. 可以进行切片操作

 

    1. 不可变,字符串是不可变的,不能像列表一样修改其中某个元素,所有对字符串的修改操作其实都是相当于生成了一份新数据。

 

补充:

1.字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如name=r’l\thf’

字符串的常用操作

字符串操作方法有非常多,但有些不常用 ,我们只讲重要的一些给大家,其它100年都用不上的有兴趣可以自己研究

  1 def capitalize(self):
  2 首字母大写
  3 def casefold(self):
  4 把字符串全变小写
  5 >> > c = 'Alex Li'
  6 >> > c.casefold()
  7 'alex li'
  8 def center(self, width, fillchar=None):
  9 >> > c.center(50, "-")
 10 '---------------------Alex Li----------------------'
 11 def count(self, sub, start=None, end=None):
 12 """
 13 S.count(sub[, start[, end]]) -> int
 14 >>> s = "welcome to apeland"
 15 >>> s.count('e')
 16 3
 17 >>> s.count('e',3)
 18 2
 19 >>> s.count('e',3,-1)
 20 2
 21 def encode(self, encoding='utf-8', errors='strict'):
 22 """
 23 编码,日后讲
 24 def endswith(self, suffix, start=None, end=None):
 25 >> > s = "welcome to apeland"
 26 >> > s.endswith("land") 判断以什么结尾
 27 True
 28 def find(self, sub, start=None, end=None):
 29 """
 30 S.find(sub[, start[, end]]) -> int
 31 Return the lowest index in S where substring sub is found,
 32 such that sub is contained within S[start:end]. Optional
 33 arguments start and end are interpreted as in slice notation.
 34 Return -1 on failure.
 35 """
 36 return 0
 37 def format(self, *args, **kwargs): # known special case of str.format
 38 >> > s = "Welcome {0} to Apeland,you are No.{1} user."
 39 >> > s.format("Eva", 9999)
 40 'Welcome Eva to Apeland,you are No.9999 user.'
 41 >> > s1 = "Welcome {name} to Apeland,you are No.{user_num} user."
 42 >> > s1.format(name="Alex", user_num=999)
 43 'Welcome Alex to Apeland,you are No.999 user.'
 44 def format_map(self, mapping):
 45 """
 46 S.format_map(mapping) -> str
 47 Return a formatted version of S, using substitutions from mapping.
 48 The substitutions are identified by braces ('{' and '}').
 49 """
 50 讲完dict再讲这个
 51 def index(self, sub, start=None, end=None):
 52 """
 53 S.index(sub[, start[, end]]) -> int
 54 Return the lowest index in S where substring sub is found,
 55 such that sub is contained within S[start:end]. Optional
 56 arguments start and end are interpreted as in slice notation.
 57 Raises ValueError when the substring is not found.
 58 """
 59 def isdigit(self):
 60 """
 61 S.isdigit() -> bool
 62 Return True if all characters in S are digits
 63 and there is at least one character in S, False otherwise.
 64 """
 65 return False
 66 def islower(self):
 67 """
 68 S.islower() -> bool
 69 Return True if all cased characters in S are lowercase and there is
 70 at least one cased character in S, False otherwise.
 71 """
 72 def isspace(self):
 73 """
 74 S.isspace() -> bool
 75 Return True if all characters in S are whitespace
 76 and there is at least one character in S, False otherwise.
 77 """
 78 def isupper(self):
 79 """
 80 S.isupper() -> bool
 81 Return True if all cased characters in S are uppercase and there is
 82 at least one cased character in S, False otherwise.
 83 """
 84 def join(self, iterable):
 85 """
 86 S.join(iterable) -> str
 87 Return a string which is the concatenation of the strings in the
 88 iterable. The separator between elements is S.
 89 """
 90 >>> n = ['alex','jack','rain']
 91 >>> '|'.join(n)
 92 'alex|jack|rain'
 93 def ljust(self, width, fillchar=None):
 94 """
 95 S.ljust(width[, fillchar]) -> str
 96 Return S left-justified in a Unicode string of length width. Padding is
 97 done using the specified fill character (default is a space).
 98 """
 99 return ""
100 def lower(self):
101 """
102 S.lower() -> str
103 Return a copy of the string S converted to lowercase.
104 """
105 return ""
106 def lstrip(self, chars=None):
107 """
108 S.lstrip([chars]) -> str
109 Return a copy of the string S with leading whitespace removed.
110 If chars is given and not None, remove characters in chars instead.
111 """
112 return ""
113 def replace(self, old, new, count=None):
114 """
115 S.replace(old, new[, count]) -> str
116 Return a copy of S with all occurrences of substring
117 old replaced by new. If the optional argument count is
118 given, only the first count occurrences are replaced.
119 """
120 return ""
121 def rjust(self, width, fillchar=None):
122 """
123 S.rjust(width[, fillchar]) -> str
124 Return S right-justified in a string of length width. Padding is
125 done using the specified fill character (default is a space).
126 """
127 return ""
128 def rsplit(self, sep=None, maxsplit=-1):
129 """
130 S.rsplit(sep=None, maxsplit=-1) -> list of strings
131 Return a list of the words in S, using sep as the
132 delimiter string, starting at the end of the string and
133 working to the front. If maxsplit is given, at most maxsplit
134 splits are done. If sep is not specified, any whitespace string
135 is a separator.
136 """
137 return []
138 def rstrip(self, chars=None):
139 """
140 S.rstrip([chars]) -> str
141 Return a copy of the string S with trailing whitespace removed.
142 If chars is given and not None, remove characters in chars instead.
143 """
144 return ""
145 def split(self, sep=None, maxsplit=-1):
146 """
147 S.split(sep=None, maxsplit=-1) -> list of strings
148 Return a list of the words in S, using sep as the
149 delimiter string. If maxsplit is given, at most maxsplit
150 splits are done. If sep is not specified or is None, any
151 whitespace string is a separator and empty strings are
152 removed from the result.
153 """
154 return []
155 def startswith(self, prefix, start=None, end=None):
156 """
157 S.startswith(prefix[, start[, end]]) -> bool
158 Return True if S starts with the specified prefix, False otherwise.
159 With optional start, test S beginning at that position.
160 With optional end, stop comparing S at that position.
161 prefix can also be a tuple of strings to try.
162 """
163 return False
164 def strip(self, chars=None):
165 """
166 S.strip([chars]) -> str
167 Return a copy of the string S with leading and trailing
168 whitespace removed.
169 If chars is given and not None, remove characters in chars instead.
170 """
171 return ""
172 def swapcase(self):
173 """
174 S.swapcase() -> str
175 Return a copy of S with uppercase characters converted to lowercase
176 and vice versa.
177 """
178 return ""
179 def upper(self):
180 """
181 S.upper() -> str
182 Return a copy of S converted to uppercase.
183 """
184 return ""
185 def zfill(self, width):
186 """
187 S.zfill(width) -> str
188 Pad a numeric string S with zeros on the left, to fill a field
189 of the specified width. The string S is never truncated.
190 """
191 return ""

字典

引子

我们学了列表 , 现在有个需求, 把你们公司每个员工的姓名、年龄、职务、工资存到列表里,你怎么存?

1 staff_list = [
2 ["Alex",23,"CEO",66000],
3 ["黑姑娘",24,"行政",4000],
4 ["佩奇",26,"讲师",40000],
5 # [xxx,xx,xx,xxx]
6 # [xxx,xx,xx,xxx]
7 # [xxx,xx,xx,xxx]
8 ]

这样存没问题,不过你要查一个人的工资的话, 是不是得把列表遍历一遍

  1. for i in staff_list:
  2. if i[0] == '黑姑娘':
  3. print(i)
  4. break

但假如你公司有2万人,如果你要找的黑姑娘正好在列表末尾,那意味着你要遍历2万次,才能找到这个信息。列表越大,查找速度越慢。

好了,现在福音来了, 接下来学要的字典可以 查询数据又快、操作又方便,是日后开发中必备神器。

字典是Python语言中唯一的映射类型。

定义:

{key1:value1,key2:value2}

  1. 1、键与值用冒号“:”分开;
  2. 2、项与项用逗号“,”分开;

示例:

  1. info = {
  2. "name":"小猿圈",
  3. "mission": "帮一千万极客高效学编程",
  4. "website": "http://apeland.com"
  5. }

特性:


    1. key-value结构

    1. key必须为不可变数据类型、必须唯一

    1. 可存放任意多个value、可修改、可以不唯一

    1. 无序

    1. 查询速度快,且不受dict的大小影响,至于为何快?我们学完hash再解释。

创建操作

1 >>>person = {"name": "alex", 'age': 20}
2 #
3 >>>person = dict(name='seven', age=20)
4 #
5 >>>person = dict({"name": "egon", 'age': 20})
6 #
7 >>> {}.fromkeys([1,2,3,4,5,6,7,8],100)
8 {1: 100, 2: 100, 3: 100, 4: 100, 5: 100, 6: 100, 7: 100, 8: 100}

增加操作

1 names = {
2 "alex": [23, "CEO", 66000],
3 "黑姑娘": [24, "行政", 4000],
4 }
5 # 新增k
6 names["佩奇"] = [26, "讲师", 40000]
7 names.setdefault("oldboy",[50,"boss",100000]) # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D

删除操作

1 names.pop("alex") # 删除指定key
2 names.popitem() # 随便删除1个key
3 del names["oldboy"] # 删除指定key,同pop方法
4 names.clear() # 清空dict

修改操作

dic['key'] = 'new_value',如果key在字典中存在,'new_value'将会替代原来的value值;
dic.update(dic2) 将字典dic2的键值对添加到字典dic中

查操作

1 dic['key'] #返回字典中key对应的值,若key不存在字典中,则报错;
2 dic.get(key, default = None)#返回字典中key对应的值,若key不存在字典中,则返回default的值(default默认为None)
3 'key' in dic #若存在则返回True,没有则返回False
4 dic.keys() 返回一个包含字典所有KEY的列表;
5 dic.values() 返回一个包含字典所有value的列表;
6 dic.items() 返回一个包含所有(键,值)元组的列表;

循环

 1 1、for k in dic.keys()
 2 2、for k,v in dic.items()
 3 3、for k in dic # 推荐用这种,效率速度最快
 4 info = {
 5 "name":"小猿圈",
 6 "mission": "帮一千万极客高效学编程",
 7 "website": "http://apeland.com"
 8 }
 9 for k in info:
10 print(k,info[k])
11 输出
12 name 小猿圈
13 mission 帮一千万极客高效学编程
14 website http://apeland.com

求长度

len(dic)

 

练习题


    1. 用你能想到的最少的代码生成一个包含100个key的字典,每个value的值不能一样

    1. {‘k0’: 0, ‘k1’: 1, ‘k2’: 2, ‘k3’: 3, ‘k4’: 4, ‘k5’: 5, ‘k6’: 6, ‘k7’: 7, ‘k8’: 8, ‘k9’: 9} 请把这个dict中key大于5的值value打印出来。

    1. 把题2中value是偶数的统一改成-1

    1. 请设计一个dict, 存储你们公司每个人的信息, 信息包含至少姓名、年龄、电话、职位、工资,并提供一个简单的查找接口,用户按你的要求输入要查找的人,你的程序把查到的信息打印出来
 

集合

定义

集合跟我们学的列表有点像,也是可以存一堆数据,不过它有几个独特的特点,令其在整个Python语言中占有一席之地,

 

    1. 里面的元素不可变,代表你不能存一个list、dict 在集合里,字符串、数字、元组等不可变类型可以存

 

    1. 天生去重,在集合里没办法存重复的元素

 

    1. 无序,不像列表一样通过索引来标记在列表中的位置 ,元素是无序的,集合中的元素没有先后之分,如集合{3,4,5}和{3,5,4}算作同一个集合

 

基于上面的特性,我们可以用集合来干2件事,去重和关系运算

语法

创建集合

1 >>> a = {1,2,3,4,2,'alex',3,'rain','alex'}
2 >>> a
3 {1, 2, 3, 4, 'alex', 'rain'}

由于它是天生去重的,重复的值你根本存不进去

帮列表去重

帮列表去重最快速的办法是什么? 就是把它转成集合,去重完,再转回列表

1 >>> b
2 [1, 2, 3, 4, 2, 'alex', 3, 'rain', 'alex']
3 >>> set(b)
4 {1, 2, 3, 4, 'alex', 'rain'}
5 >>>
6 >>> b = list(set(b)) #一句代码搞定
7 >>> b
8 [1, 2, 3, 4, 'alex', 'rain']

增删改查

 1 >>> a
 2 {1, 2, 3, 4, 'alex', 'rain'}
 3 #新增
 4 >>> a.add('黑姑娘')
 5 #删除discard
 6 >>> a
 7 {2, 3, '黑姑娘', 'alex', 'rain'}
 8 >>> a.discard('rain') #删除一个存在的值
 9 >>> a.discard('rain2') #如果这个值不存在,do nothing.
10 >>> a
11 {2, 3, '黑姑娘', 'alex'}
12 >>>
13 #随机删除,少用,或特定场景用
14 >>> a.pop() #删除并返回
15 1
16 #删除remove
17 >>> a.remove(4)
18 #
19 >>> a
20 {2, 3, '黑姑娘', 'alex', 'rain'}
21 >>> 'alex' in a
22 True
23 #
24 呵呵,不能改。。。

关系运算

1 s_1024 = {"佩奇","老男孩","海峰","马JJ","老村长","黑姑娘","Alex"}
2 s_pornhub = {"Alex","Egon","Rain","马JJ","Nick","Jack"}
3 print(s_1024 & s_pornhub) # 交集, elements in both set
4 print(s_1024 | s_pornhub) # 并集 or 合集
5 print(s_1024 - s_pornhub) # 差集 , only in 1024
6 print(s_pornhub - s_1024) # 差集, only in pornhub
7 print(s_1024 ^ s_pornhub) # 对称差集, 把脚踩2只船的人T出去

两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:

1 print(s_1024.isdisjoint(s_pornhub)) # 判断2个集合是不是不相交,返回True or False
2 print(s_1024.issubset(s_pornhub)) # 判断s_1024是不是s_pornhub的子集,返回True or False
3 print(s_1024.issuperset(s_pornhub)) # 判断s_1024是不是s_pornhub的父集,返回True or False
 

 

猜你喜欢

转载自www.cnblogs.com/PolarIce/p/11919012.html