Data structure Python-04-

A digital

Integer

  Python integers of any size can be treated, including, of course negative integer representation in the program and written mathematical exactly the same, for example: 1, , 100, -8080, 0and the like.

  Due to the use of a binary computer, so sometimes expressed in hexadecimal integer more convenient, hexadecimal with 0xthe prefix and 0-9, af, for example: 0xff00, 0xa5b4c3d2and so

Float

  I.e. decimal floating-point, floating-point number is called, because when expressed in terms of scientific notation, a floating decimal point position is variable, for example, 1.23x10 . 9 and 12.3x10 . 8 are completely identical. Floating-point math can be written, such as 1.23, 3.14, -9.01, and so on. However, for very large or very small float, it must be expressed in scientific notation, with the 10 e alternative, 1.23x10 . 9 is 1.23e9, or 12.3e8, 0.000012 can be written 1.2e-5, and the like.

  Integer and floating point numbers in a computer internal storage approach is different, integer arithmetic is always accurate (division Is it also accurate? Yes!), And floating-point operations may have rounding error.

Common methods:

  • int string into digital
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = '123'
print(type(a), a)
a = int(a)
print(type(a), a)

#输出
<class 'str'> 123
<class 'int'> 123
  • bit_length current digital binary representation with at least a few
#!/usr/bin/env python
# -*- coding:utf-8 -*-
age = 10
r = age.bit_length()
print(r)

#输出
4

 Second, the string

1. common method

  • capitalize    the first character uppercase

    mystr.capitalize()

  • casefold lower    conversion mystr in all uppercase characters to lowercase casefold can identify special characters

    mystr.lower()

  • upper conversion mystr lowercase letters to uppercase

    mystr.upper()

  • Case conversion swapcase

    mystr.swapcase()

Test = 'sFHVahKHJss' 
in = test.swapcase () 
print (in) 

#输出
SfhvAHkhjSS
  • Returns a string of the original center center, length and width using fillchar filled new string

    mystr.center(width, fillchar=” ”)

  • return str count the number of times between the start and the end appears in mystr inside

    mystr.count(str, start=0, end=len(mystr))

  • Endswith check whether the string obj end, a return True, otherwise False.

    mystr.endswith(obj)

  • Startwith check whether a string begins with obj, is True is returned, otherwise it returns False

    mystr.startswith(obj)

  • find     detector is included in mystr str, if the index value comprising a return start, otherwise -1

    mystr.find(str, start=0, end=len(mystr))

  • index with the find () method of the same, but if str is not an exception will be reported in mystr

    mystr.index(str, start=0, end=len(mystr))

  • format string formatted
#!/usr/bin/env python
# -*- coding:utf-8 -*-
test = 'my name is {name},age is {age}'
print(test)
mstr = test.format(name='Tom', age=15)
print(mstr)

#输出
my name is {name},age is {age}
my name is Tom,age is 15
# Format of the three kinds of play 
RES1 = '{} {} {}'. The format ( 'Egon', 18 is, 'MALE') 
RES2 = '{}. 1. 1} {0} {'. The format ( 'Egon', 18 is , 'MALE') 
RES3 = '{name} {Age} {Sex}'. the format (Sex = 'MALE', name = 'Egon', Age = 18 is) 
Print (RES1) 
Print (RES2) 
Print (RES3) 

# output 
Egon MALE 18 is 
18 is 18 is Egon 
Egon 18 is MALE
  • format_map similar format, but the incoming parameter is a dictionary
#!/usr/bin/env python
# -*- coding:utf-8 -*-
test = 'my name is {name},age is {age}'
print(test)
mstr = test.format_map({"name":"Tom", "age":"15"})
print(mstr)

#输出
my name is {name},age is {age}
my name is Tom,age is 15
  • replace replace mystr in str1 into str2, if the count is specified, the replacement does not exceed count times

    mystr.replace(str1, str2,  mystr.count(str1))

name = 'alex say :i have one tesla,my name is alex'
print(name.replace('alex', 'SB', 1))

#输出
SB say :i have one tesla,my name is alex
  • split    takes str myStr slice delimiter, if maxsplit value is specified, only the partition maxsplit substrings

    mystr.split(str=" ", maxsplit)

= name 'the root: X: 0: 0 :: / the root: / bin / the bash' 
Print (name.split ( ':')) # default delimiter is a space 
name = 'C: / a / b / c / d .txt '# just get the top-level directory 
Print (name.split (' / ',. 1)) 

# output 
[' root ',' x ' ,' 0 ',' 0 ',' ',' / root ', '/ bin / the bash'] 
[ 'C:', 'A / B / C / d.txt']
  • rsplit similar split, but the right start
  • title string of each word capitalized

    mystr.title()

  • Returns a string ljust original left-justified and filled using fillchar width new string length

    mystr.ljust (width, fillchar = "")

  • Returns a string rjust original right-aligned, a length and width using fillchar filled new string

    mystr.rjust(width, fillchar=” ”)

  • zfill Returns a specified length of the original string right justified, padded with zeros in front of

    mystr.zfill(width)

  • lstrip left mystr delete whitespace   can also remove the specified character

    mystr.lstrip()

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
test = 'asdfghh'
v = test.lstrip('8assdf') # 消除所有匹配到的字符
print(v)

#输出
ghh
  • rstrip    删除 mystr 右边的空白字符   也可以去除指定的字符

    mystr.rstrip()

  • strip    删除mystr字符串两端的空白字符   也可以去除指定的字符

    mystr.strip()

  • rfind    类似于 find()函数,不过是从右边开始查找

    mystr.rfind(str, start=0,end=len(mystr) )

  • rindex   类似于 index(),不过是从右边开始.

    mystr.rindex( str, start=0,end=len(mystr))

  • partition    把mystr以str分割成三部分,str前,str和str后

    mystr.partition(str)

 

test = 'ahjsyklsuiyska'
v = test.partition('s')
print(v)

#输出
('ahj', 's', 'yklsuiyska')

 

  • rpartition    类似于 partition()函数,不过是从右边开始.

    mystr.rpartition(str)

  • splitlines    按照行分隔,返回一个包含各行作为元素的列表

    mystr.splitlines()

 

test = 'ahjsykls\nuiyska\nvjshgk\ndhvgks'
v1 = test.splitlines(True)
print(v1)
v2 = test.splitlines(False)
print(v2)

#输出
['ahjsykls\n', 'uiyska\n', 'vjshgk\n', 'dhvgks']
['ahjsykls', 'uiyska', 'vjshgk', 'dhvgks']

 

  • isupper    判断字符串否全是大写字母

    mystr.isupper()

  • islower    判断字符串否全是小写字母

    mystr.islower()

  • isalpha    如果 mystr 所有字符都是字母 则返回 True,否则返回 False

    mystr.isalpha()

  • isdigit    isdecimal    isnumeric    如果 mystr 只包含数字则返回 True 否则返回 False。isdigit可以判断一些特殊字符例如②。 isnumeric可以判断中文数字例如二。

    mystr.isdigit()

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
test = '②'
v1 = test.isdecimal()
v2 = test.isdigit()
print(v1, v2)

#输出
False True
test = '二'
v1 = test.isdecimal()
v2 = test.isdigit()
v3 = test.isnumeric()
print(v1, v2, v3)

#输出
False False True
  • isalnum    如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False

    mystr.isalnum()

  • isspace    如果 mystr 中只包含空格,则返回 True,否则返回 False

    mystr.isspace()

  • istitle    如果字符串的每个单词的首字母都是大写,则返回True,否则返回False

    mystr.istitle()

  • isprintable    判断字符串是否能够被打印

    mystr.isprintable()

test = '\n'
v = test.isprintable()
print(v)

#输出
False
  • join    将字符串、元组、列表中的元素以mystr连接生成一个新的字符串

    mystr.join(str)

mystr = ' '
print(mystr.join(["haha", "hehe", "heihei"]))
mystr = '-'
print(mystr.join(["haha", "hehe", "heihei"]))

# 运行结果:
haha hehe heihei
haha-hehe-heihei
  •  expandtabs 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。从头开始数,数到第一个\t正好为8个空格,不足则补空格,如果还有\t,接着从第一个\t数到第二个\t仍然为8个空格,以此类推直到最后一个\t结束。
    S.expandtabs([tabsize=8])
#!/usr/bin/python3
 
S = "this is\tstring example....wow!!!"
print ("原始字符串: " + S)
print ("替换 \\t 符号: " +  S.expandtabs())
print ("使用16个空格替换 \\t 符号: " +  S.expandtabs(16))
"""
以上实例输出结果如下:
原始字符串: this is     string example....wow!!!
替换 \t 符号: this is string example....wow!!!
使用16个空格替换 \t 符号: this is         string example....wow!!!
"""
#!/usr/bin/env python
#-*- encoding:utf-8 -*-

S = "username\temail\tpassword\nlaiying\[email protected]\t123\nlaiying\[email protected]\t123\nlaiying\[email protected]\t123"
v = S.expandtabs(20)
print(v)

 

  • translate   替换字符串中指定的字符
test = 'ahjsykliuiyjka'
m = str.maketrans('aeiou','12345')
v = test.translate(m)
print(v)

#输出
1hjsykl353yjk1

 重点:

  1、strip,lstrip,rstrip

  2、lower,upper

  3、startswith,endswith

  4、format的三种玩法

  5、split,rsplit

  6、join

  7、replace

  8、isdigit

2. 下标切片

字符串中"下标"的使用

字符串实际上就是字符的数组,所以支持下标索引。

如果有字符串:name = 'abcdef',在内存中的实际存储如下:

如果想取出部分字符,那么可以通过下标的方法,(注意python中下标从 0 开始)

name = 'abcdef'
print(name[0])
print(name[1])
print(name[2])

运行结果:
a
b
c

切片

切片是指对操作的对象截取其中一部分的操作。

切片的语法:变量名[起始:结束:步长]

注意:选取的区间属于左闭右开型,即从"起始"位开始,到"结束"位的前一位结束(包含起始位本身但不包含结束位本身)。结束位可以不写,那么默认按照步长一直到末尾。

如果取出一部分,则可以在中括号[]中

示例1:
name = 'abcdef'
print(name[0:3])  # 取下标0~2 的字符
运行结果:
abc

示例2:
name = 'abcdef'
print(name[2:])  # 取下标为2开始到最后的字符
运行结果:
cdef

示例3:
name = 'abcdef'
print(name[len(name)-1])  # 取下标为字符长度-1的字符
print(name[-1])  # 取下标为倒数第一个的字符
运行结果:
f
f

示例4:
name = 'abcdef'
print(name[1:-1])  # 取第2个到倒数第2个字符切片
print(name[0::2])  # 从第一个字符开始每次步长为2取切片
运行结果:
bcde
ace

示例5:
name = 'abcdef'
print(name[-1:-5:-1])  # 逆向取倒数第一个到倒数第4个字符切片
print(name[-1::-1])  # 逆向取倒数第一个到末尾的字符切片
print(name[::-1])  # 倒序字符的切片
运行结果:
fedc
fedcba
fedcba

 三、列表

1. 添加元素("增"append, extend, insert)

append:通过append可以向列表添加元素,并且默认添加在列表末尾。

示例:

namesList = ['tom', 'jerry', 'jhon']
print("----添加之前,列表中的元素----")
print(namesList)
print("----添加之后,列表中的元素----")
namesList.append("james")
print(namesList)
运行结果: ----添加之前,列表中的元素---- ['tom', 'jerry', 'jhon'] ----添加之后,列表中的元素---- ['tom', 'jerry', 'jhon', 'james']

extend:通过extend可以将另一个集合中的元素逐一添加到列表中

示例:

print("----使用append添加----")
a = ['a', 'b', 'c']
b = ['1', '2', '3']
a.append(b)
print(a)
print("----使用extend添加----")
a = ['a', 'b', 'c']
b = ['1', '2', '3']
a.extend(b)
print(a)

运行结果:
----使用append添加----
['a', 'b', 'c', ['1', '2', '3']]
----使用extend添加----
['a', 'b', 'c', '1', '2', '3']

insert:insert(index, object) 在指定位置index前插入元素object

示例:

a = ['a', 'b', 'c']
a.insert(1, "haha")
print(a)

运行结果:
['a', 'haha', 'b', 'c']

2. 删除元素("删"del, pop, remove,clear)

del:根据下标进行删除

示例:

movieName = ['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
print('------删除之前------')
print(movieName)
print('------删除之后------')
del movieName[2]
print(movieName)

运行结果:
------删除之前------
['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
------删除之后------
['绿巨人', '钢铁侠', '雷神', '洛基']

pop:删除最后一个元素

示例:

movieName = ['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
print('------删除之前------')
print(movieName)
print('------删除之后------')
movieName.pop()  # 也可以传入下标作为参数,删除该下标的元素
print(movieName)

运行结果:
------删除之前------
['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
------删除之后------
['绿巨人', '钢铁侠', '超人', '雷神']

remove:根据元素的值进行删除

示例:

movieName = ['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
print('------删除之前------')
print(movieName)
print('------删除之后------')
movieName.remove('超人')
print(movieName)

运行结果:
------删除之前------
['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
------删除之后------
['绿巨人', '钢铁侠', '雷神', '洛基']

clear:清空所有元素

mlist = [1, 2, 3, 4, 5, 6, 7]
mlist.clear()
print(mlist)

运行结果:
[]

3. 修改元素("改")

修改元素的时候,要通过下标来确定要修改的是哪个元素,然后对其重新赋值

示例:

movieName = ['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
print('------修改之前------')
print(movieName)
print('------修改之后------')
movieName[2] = '美国队长'
print(movieName)

运行结果:
------修改之前------
['绿巨人', '钢铁侠', '超人', '雷神', '洛基']
------修改之后------
['绿巨人', '钢铁侠', '美国队长', '雷神', '洛基']

4. 查找元素("查"in, not in, index, count)

in, not in

示例:

name_list = ['tom', 'jerry', 'alice', 'james']
print('tom' in name_list)
print('tom' not in name_list)

运行结果:
True
False

index, count

示例:

name_list = ['tom', 'jerry', 'alice', 'james', 'jerry']
print(name_list.index('jerry', 1, 3))
print(name_list.index('jerry', 4, 6))
print(name_list.count('jerry'))

运行结果:
1
4
2

5. 排序(sort, reverse)

  • sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。
  • reverse方法是将list逆置。

示例:

a = [1, 4, 2, 3, 6, 5, 9, 8, 7]
print('----原列表----')
print(a)
print('----reverse----')
a.reverse()
print(a)
print('----sort----')
a.sort()
print(a)
print('----sort(reverse=True)----')
a.sort(reverse=True)
print(a)

运行结果:
----原列表----
[1, 4, 2, 3, 6, 5, 9, 8, 7]
----reverse----
[7, 8, 9, 5, 6, 3, 2, 4, 1]
----sort----
[1, 2, 3, 4, 5, 6, 7, 8, 9]
----sort(reverse=True)----
[9, 8, 7, 6, 5, 4, 3, 2, 1]

 四、元组

python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号,列表使用方括号。

tuple = (1, 2, 3, 4)

1. 访问元组

tuple = (1, 2, 3, 4)
print(tuple[0])
print(tuple[2])

运行结果:
1
3

2. 元组的内置函数count, index

tuple = ('tom', 'jerry', 'alice', 'james')
print(tuple.index('alice', 1, 3))
print(tuple.count('jerry'))

运行结果:
2
1

 五、字典

字典的创建
person = {"name": "sb", 'age': 18}
或
person = dict(name='sb', age=18)
person = dict({"name": "sb", 'age': 18})
person = dict((['name','sb'],['age',18]))

{}.fromkeys(seq,100) #不指定100默认为None
注意:

>>> dic={}.fromkeys(['k1','k2'],[])
>>> dic
{'k1': [], 'k2': []}
>>> dic['k1'].append(1)
>>> dic
{'k1': [1], 'k2': [1]}

变量info为字典类型:

info = {'name':'孙悟空', 'id':100, 'sex':'男', 'address':'花果山'}

说明:

  • 字典和列表一样,也能够存储多个数据
  • 列表中找某个元素时,是根据下标进行的。字典中找某个元素时,是根据'名字'(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')
  • 字典的每个元素由2部分组成,键:值。例如 'name':'孙悟空' ,'name'为键,'孙悟空'为值

1. 根据键访问值

info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print(info['name'])
print(info['address'])

运行结果:
孙悟空
花果山

若访问不存在的键,则会报错:
info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print(info['haha'])

运行结果:
Traceback (most recent call last):
  File "X:/xxx/xxx/xxx.py", line 2, in <module>
    print(info['haha'])
KeyError: 'haha'

在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值:
info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print(info.get('name'))
print(info.get('haha'))
print(info.get('haha', 'haha'))

运行结果:
孙悟空
None
haha

2. 修改元素

字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改

info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print('----修改前----')
print(info)
print('----修改后----')
info['name'] = "齐天大圣"
print(info)

运行结果:
----修改前----
{'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
----修改后----
{'name': '齐天大圣', 'id': 100, 'sex': '男', 'address': '花果山'}

3. 添加元素

如果在使用变量名['键'] = 数据时,这个“键”在字典中,不存在,那么就会新增这个元素

info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print('----修改前----')
print(info)
print('----修改后----')
info['age'] = 500
print(info)

运行结果:
----修改前----
{'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
----修改后----
{'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山', 'age': 500}

4. 删除元素

del删除指定的元素

info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print('----删除前----')
print(info)
print('----删除后----')
del info['sex']
print(info)

运行结果:
----删除前----
{'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
----删除后----
{'name': '孙悟空', 'id': 100, 'address': '花果山'}

clear清空整个字典

info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
print('----清空前----')
print(info)
print('----清空后----')
info.clear()
print(info)

运行结果:
----清空前----
{'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}
----清空后----
{}

pop删除指定元素,若删除的元素不存在,可以指定返回值

dic = {
    'k1': 'v1',
    'k2': 'v2'
}
v = dic.pop('k1')
print(dic, v)
# 运行结果
{'k2': 'v2'} v1

dic = {
    'k1': 'v1',
    'k2': 'v2'
}
v = dic.pop('k111', 1)
print(dic, v)
# 运行结果
{'k1': 'v1', 'k2': 'v2'} 1

5. keys

返回一个包含字典所有KEY的列表

>>> info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}

>>> info.keys()

dict_keys(['name', 'id', 'sex', 'address'])

>>> 

6. values

返回一个包含字典所有value的列表

>>> info = {'name': '孙悟空', 'id': 100, 'sex': '男', 'address': '花果山'}

>>> info.values()

dict_values(['孙悟空', 100, '男', '花果山'])

>>> 

7. items

返回一个包含所有(键,值)元组的列表

>>> info = {'name': '孙悟空', 'address': '花果山'}

>>> info.items()

dict_items([('name', '孙悟空'), ('address', '花果山')])

>>> 

8. has_key和in

python3去除了has _key替换为in

如果key在字典中,返回True,否则返回False

>>> info = {'name': '孙悟空', 'address': '花果山'}

>>> 'name' in info

True

>>> 'age' in info

False

>>> 

看看python2中的has_key,当然python2中in也可以使用

>>> info = {'name': '孙悟空', 'address': '花果山'}

>>> 'name' in info

True

>>> info.has_key('name')

True

>>> info.has_key('age')

False

>>> 

9. update

dic = {
    'k1': 'v1',
    'k2': 'v2'
}
dic.update({'k1': 123, 'k3': 456})
print(dic)
# 运行结果 {'k1': 123, 'k2': 'v2', 'k3': 456}

10. 字典遍历

info = {'name': '孙悟空', 'address': '花果山'}
print('----遍历字典的key(键)----')
for key in info.keys():
    print(key, end='\t')
print()
print('----遍历字典的value(值)----')
for value in info.values():
    print(value, end='\t')
print()
print('----遍历字典的项(元素)----')
for item in info.items():
    print(item, end='\t')

运行结果:
----遍历字典的key(键)----
name    address
----遍历字典的value(值)----
孙悟空   花果山  
----遍历字典的项(元素)----
('name', '孙悟空')  ('address', '花果山')

六、集合

 1. 定义

  定义:由不同元素组成的集合,集合中是一组无序排列的可hash值,可以作为字典的key

  特点:

    • 不同元素组成
    • 无序
    • 每个元素必须是不可变类型

2. 集合的创建

   {1,2,3,1}
  或
  定义可变集合set
  >>> set_test=set('hello')
  >>> set_test
  {'l', 'o', 'e', 'h'}
  改为不可变集合frozenset
  >>> f_set_test=frozenset(set_test)
  >>> f_set_test
  frozenset({'l', 'e', 'h', 'o'})

3.  常用操作

add    添加元素

s = {1, 2, 3}
s.add(4)
print(s)

运行结果
{1,2,3,4}

pop    随机删除一个元素

s = {'b', 123, 2, 3, 'a'}
s.pop()
print(s)

#运行结果
{3, 'b', 'a', 123}
 

remove    删除指定元素,删除不存在的元素时会报错

s = {'b', 123, 2, 3, 'a'}
s.remove('a')
print(s)

# 运行结果
{2, 3, 'b', 123}

discard    删除指定元素,删除不存在的元素时不会报错

 

intersection  或  &     交集

s = {'b', 123, 2, 3, 'a'}
b = {'a', 2, 5, 123}
sb = s.intersection(b)
print(sb)
print(s & b)
# 运行结果
{2, 123, 'a'}
{2, 123, 'a'}

union  或  |    并集

s = {'b', 123, 2, 3, 'a'}
b = {'a', 2, 5, 123}
sb = s.union(b)
print(sb)
print(s | b)

# 运行结果
{2, 3, 'a', 5, 'b', 123}
{2, 3, 'a', 5, 'b', 123}

difference  或  -    差集

s = {'b', 123, 2, 3, 'a'}
b = {'a', 2, 5, 123}
sb = s - b
bs = b - s
print(sb, bs)

# 运行结果
{3, 'b'} {5}

symmetric_difference   或  ^     交叉补集(两个集合不共有的部分)

s = {'b', 123, 2, 3, 'a'}
b = {'a', 2, 5, 123}
sb = s.symmetric_difference(b)
print(sb)

# 运行结果
{3, 5, 'b'}

difference_update     返回两集合的差集

s = {'b', 123, 2, 3, 'a'}
b = {'a', 2, 5, 123}
s.difference_update(b) # 将两集合的差集返回给s
print(s)

# 运行结果
{3, 'b'}

isdisjoint     如果两集合的交集为空集,返回True

s = {'b', 2, 3, }
b = {'a', 5, 123}
v = s.isdisjoint(b)
print(v)

# 运行结果
True

issubset    如果s1是s2的子集,返回True

s1 = {1, 2}
s2 = {1, 2, 3}
v = s1.issubset(s2)
print(v)

#运行结果
True

 issuperset    如果s1包含s2父集,返回True

s1 = {1, 2}
s2 = {1, 2, 3}
v = s1.issuperset(s2)
print(v)
# 运行结果 
False

update    更新

s1 = {1, 2}
s2 = {1, 2, 3}
s1.update(s2)
print(s1)

# 运行结果
{1,2,3}

 

Guess you like

Origin www.cnblogs.com/lsf123456/p/11132809.html