美文网首页简友广场
day-007--字符串和常用数据结构

day-007--字符串和常用数据结构

作者: 搬砖程序员 | 来源:发表于2019-07-12 01:51 被阅读0次

字符串和常用数据结构

这个地方得好好看,正常得就是在操作字符串和这些类型的使用

1.字符串一些操作

字符串操作

def main():
    str1 = 'hello world!'
    str2 = 'abc123456'
    str3 = '   testspace   '
    #do demo
if __name__ == '__main__':
    main()
字符串操作 描述 举例 结果
len() 获取字符串长度 print(len(str1)) 13
capitalize() 首字母大写 print(str1.capitalize()) Hello, world!
upper() 全部大写 print(str1.upper()) HELLO, WORLD!
title() 首个单词大写 print(str1.title()) HELLO, world!
lower() 全部小写 print(str1.lower()) hello world!
find(str) 查找子串 ,不包含返回-1 print(str1.find('or')) 8
startswith(str) 是否以字符串开头 print(str1.startswith('He')) False
endswith(str) 是否以字符串结尾 print(str1.endswith('!')) True
center(len, char) 以指定的宽度居中并在两侧填充指定的字符 print(str1.center(50, '*')) ***hello, world!****
rjust(l, c) ljust(l, c) 靠左,靠右多宽,填充指定字符 print(str1.rjust(20, ' ')) *******hello, world!
str2[] 从字符串里去指定位置的字符或者串 print(str2[2]) c
[] [2:5] [2:] [2::2] [::2] [::-1] [-3:-1] 截取字符串中的一部分,遵循左闭右开原则 一会看下面执行结果

下面有个讲的很详细的 传送门

上代码:

import os
import time
def main():

    # 这一片是字符串
    str1 = 'hello, world!'
    # 通过len函数计算字符串的长度
    print(len(str1))  # 13
    # 获得字符串首字母大写的拷贝
    print(str1.capitalize())  # Hello, world!
    # 获得字符串变大写后的拷贝
    print(str1.upper())  # HELLO, WORLD!
    # 从字符串中查找子串所在位置
    print(str1.find('or'))  # 8
    print(str1.find('shit'))  # -1
    # 与find类似但找不到子串时会引发异常
    # print(str1.index('or'))
    # print(str1.index('shit'))
    # 检查字符串是否以指定的字符串开头
    print(str1.startswith('He'))  # False
    print(str1.startswith('hel'))  # True
    # 检查字符串是否以指定的字符串结尾
    print(str1.endswith('!'))  # True
    # 将字符串以指定的宽度居中并在两侧填充指定的字符
    print(str1.center(20, '*'))
    # 将字符串以指定的宽度靠右放置左侧填充指定的字符
    print(str1.rjust(20, '*'))
    print(str1.ljust(20, ' '))
    str2 = 'abc123456'
    # 从字符串中取出指定位置的字符(下标运算)
    print(str2[2])  # c
    # 字符串切片(从指定的开始索引到指定的结束索引)
    print(str2[2:5])  # c12
    print(str2[2:])  # c123456
    print(str2[2::2])  # c246
    print(str2[::2])  # ac246
    print(str2[::-1])  # 654321cba
    print(str2[-3:-1])  # 45
    # 检查字符串是否由数字构成
    print(str2.isdigit())  # False
    # 检查字符串是否以字母构成
    print(str2.isalpha())  # False
    # 检查字符串是否以数字和字母构成
    print(str2.isalnum())  # True
    str3 = '  jackfrued@126.com '
    print(str3)
    # 获得字符串修剪左右两侧空格的拷贝
    print(str3.strip())

    # content = '北京欢迎你为你开天辟地······'
    # while True:
    #     # 清理屏幕上的输出
    #     os.system('cls')  # os.system('clear')
    #     print(content)
    #     # 休眠200毫秒
    #     time.sleep(0.2)
    #     content = content[1:] + content[0]


if __name__ == '__main__':
    main()

执行结果:

13
Hello, world!
HELLO, WORLD!
8
-1
False
True
True
***hello, world!****
*******hello, world!
hello, world!       
c
c12
c123456
c246
ac246
654321cba
45
False
False
True
  jackfrued@126.com 
jackfrued@126.com

2.列表

列表是Python中最基本的数据结构。列表中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

格式是这个样子,塞啥进去都行

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

2.1列表的操作,和上面字符串操作方式基本一致 主要可以分为增删改查

2.1.1访问列表的值 通过[] --

实例:

    list1 = ['one', 'two', 1, 2 , 'xxx', 'yyy', 1000, 1234]
    print(type(list1))
    print('list [0]:', list1[0], 'list[-2]:',list1[-2])
    print('list[1:]', list1[1:], 'list[0:2]', list1[0:2], 'list1[::2]', list1[::2], '\n', 'list[::-1]', list1[::-1],
          'list1[7::-1]', list1[7::-1])

结果:

<class 'list'>
list [0]: one list[-2]: 1000
list[1:] ['two', 1, 2, 'xxx', 'yyy', 1000, 1234] list[0:2] ['one', 'two'] list1[::2] ['one', 1, 'xxx', 1000] 
 list[::-1] [1234, 1000, 'yyy', 'xxx', 2, 1, 'two', 'one'] list1[7::-1] [1234, 1000, 'yyy', 'xxx', 2, 1, 'two', 'one']

[]这个操作符是左闭右开区间,要想访问最右边的如果是正向,就最大index加1,如果是反向,就不写

2.1.2更新列表,直接赋值 --

不能超过列表的最大下标,不然会报列表溢出异常

实列:

   list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234]
    print(list1)
    list1[1] = 123
    list1[2] = '123'
    list1[0] = 'two'
    list1[4] = 2222
    print(list1)

结果:

['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234]
['two', 123, '123', 2, 2222, 'yyy', 1000, 1234]

类型啊,内容都可以改

2.1.3增加列表项,通过append(obj)追加和insert(index,obj)插入 来实现 --

看实例:

 list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234]
    print(list1)
    list1.append('test_append')
    list1.insert(3, 'test_insert')
    print(list1)

执行结果:

['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234]
['one', 'two', 1, 'test_insert', 2, 'xxx', 'yyy', 1000, 1234, 'test_append']

这个appendinsert都是国际惯例

2.1.4 删除,可以用delremovepopclear 这些来实现,具体看实例 --

实例:

       list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
    print(list1)
    del list1[0]  # 删除制定的元素
    print(list1)
    list1.remove(1234)  # 清除元素,你得知道你是啥 或者 改成 list1.remove(list1[6]) 这样
    print(list1)
    list1.pop()  # 出栈的操作,竟然不支持push,奇怪,pop(index = -1)
    print(list1)
    list1.pop(1)  # 同上
    print(list1)
    list1.clear()  # 一了百了了
    print(list1)

['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
['two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
['two', 1, 2, 'xxx', 'yyy', 1000, 'test_del']
['two', 1, 2, 'xxx', 'yyy', 1000]
['two', 2, 'xxx', 'yyy', 1000]
[]

怎删改查就这样了,也就这么多操作了,这部分基本都是对列表元素的操作,下面一部分是对列表的操作

2.2对列表的一些操作,脚本操作符,截取与拼接,嵌套列表

2.2.1 操作符
Python 表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print(x, end=" ") 1 2 3 迭代
2.2.2 截取与拼接
L=['Google', 'Runoob', 'Taobao']
Python 表达式 结果 描述
L[2] 'Taobao' 读取第三个元素
L[-2] 'Runoob' 从右侧开始读取倒数第二个元素: count from the right
L[1:] ['Runoob', 'Taobao'] 输出从第二个元素开始后的所有元素

拼接使用加号

实例:

    list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
    print(list1)
    list1 += list1
    print(list1)

结果:

['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 'one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
2.2.3 嵌套列表 就是可以列表里套列表,俄罗斯套娃

直接上实例:

    list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
    print(list1)
    list2 = [list1,list1]
    print(list2)

执行结果:

['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
[['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del'], ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']]

2.3 对列表有用的一些函数和列表的方法

  • python包含以下函数:
    点链接可以跳转
函数 说明
len(list) 列表元素个数
max(list) 返回列表元素最大值,必须只包含数字或者只包含字母,不能混
min(list) 返回列表元素最小值,必须只包含数字或者只包含字母,不能混
list(seq) 将元组转换为列表

实例

    list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del']
    print(len(list1))
    # print(max(list1)) # 不能既包含数字又包含字母
    list_max_min = ['a', 'b', 'c', 'd']
    print(max(list_max_min))
    print(min(list_max_min))
    list_max_min = ['1', '2', '3', '4']
    print(max(list_max_min))
    print(min(list_max_min))
    list_max_min = [1, 2, 3, 4]
    print(max(list_max_min))
    print(min(list_max_min))
    seq = (1, '1', 'test_seq')
    print(seq)
    print(list(seq))

结果:

9
d
a
4
1
4
1
(1, '1', 'test_seq')
[1, '1', 'test_seq']
  • Python包含以下方法:
方法 描述
list.append(obj) 在列表末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
list.insert(index, obj) 将对象插入列表
list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项
list.reverse() 反向列表中元素
list.sort( key=None, reverse=False) 对原列表进行排序
list.clear() 清空列表
list.copy() 复制列表

实例:

list1 = ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234]
    list1.append('test_append')
    print('list1.append(\'test_append\')', list1)
    print('list1.count(1234)', list1.count(1234))
    print('list1.count(list1[7]', list1.count(list1[7]))
    list1.extend((1, 2, 3, 4))
    print('list1.extend((1, 2, 3, 4))', list1)
    print('list1.index(1)', list1.index(1))
    # print(list1.index(-1)) 不能这么玩
    list1.insert(1,'test_insert')
    print('list1.insert(1,\'test_insert\')',list1)
    list1.pop()
    print('list1.pop()', list1)
    list1.pop(-3)
    print('list1.pop(-3)', list1)
    list1.remove('one')
    print('list1.remove(\'one\')', list1)
    list1.remove(list1[1])
    print('list1.remove(list1[1])', list1)
    list1.reverse()
    print('list1.reverse()', list1)
    list_sort = [1, 3, 7, 2, 10, 6]
    list_sort.sort(reverse=True)
    print('list_sort.sort(reverse=True)', list_sort)
    list2 = list1.copy()
    print('list2 = list1.copy()', list2)
    list2.clear()
    print('list2.clear()', list1)

结果:

list1.append('test_append') ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append']
list1.count(1234) 2
list1.count(list1[7] 2
list1.extend((1, 2, 3, 4)) ['one', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 1, 2, 3, 4]
list1.index(1) 2
list1.insert(1,'test_insert') ['one', 'test_insert', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 1, 2, 3, 4]
list1.pop() ['one', 'test_insert', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 1, 2, 3]
list1.pop(-3) ['one', 'test_insert', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 2, 3]
list1.remove('one') ['test_insert', 'two', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 2, 3]
list1.remove(list1[1]) ['test_insert', 1, 2, 'xxx', 'yyy', 1000, 1234, 'test_del', 1234, 'test_append', 2, 3]
list1.reverse() [3, 2, 'test_append', 1234, 'test_del', 1234, 1000, 'yyy', 'xxx', 2, 1, 'test_insert']
list_sort.sort(reverse=True) [10, 7, 6, 3, 2, 1]
list2 = list1.copy() [3, 2, 'test_append', 1234, 'test_del', 1234, 1000, 'yyy', 'xxx', 2, 1, 'test_insert']
list2.clear() [3, 2, 'test_append', 1234, 'test_del', 1234, 1000, 'yyy', 'xxx', 2, 1, 'test_insert']

列表大概就这么些

3.元组类型

Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

格式就是这个样子的

    tup1 = ('Google', 'Runoob', 1997, 2000);
    print(tup1)
    tup2 = (1, 2, 3, 4, 5);
    tup3 = "a", "b", "c", "d";  # 不需要括号也可以
    print(type(tup3))
    tup4 = (50)
    print(tup4)
    print(type(tup4))
    tup5 = (50,)
    print(tup5)
    print(type(tup5))

结果:

('Google', 'Runoob', 1997, 2000)
<class 'tuple'>
50
<class 'int'>
(50,)
<class 'tuple'>

3.1访问元祖

通过[]来访问下标访问元组中的值

实例:

    tup1 = ('Google', 'Runoob', 1997, 2000);
    print(tup1)
    print('tupl[0]', tup1[0])
    print('tup1[1:3]', tup1[1:3])
    print('tupl[:]', tup1[:])
    print('tup1[::]', tup1[::])
    print('tup1[::2]', tup1[::2])
    print('tup1[::-1]', tup1[::-1])
    print('tup1[::-2]', tup1[::-2])

结果:

('Google', 'Runoob', 1997, 2000)
tupl[0] Google
tup1[1:3] ('Runoob', 1997)
tupl[:] ('Google', 'Runoob', 1997, 2000)
tup1[::] ('Google', 'Runoob', 1997, 2000)
tup1[::2] ('Google', 1997)
tup1[::-1] (2000, 1997, 'Runoob', 'Google')
tup1[::-2] (2000, 'Runoob')

3.2修改元组

元组张的元素没法修改的,可以连接增加元组

实例:

    tup1 = ('Google', 'Runoob', 1997, 2000);
    print(tup1)
    tup6 = tup1+tup1
    print(tup6)
('Google', 'Runoob', 1997, 2000)
('Google', 'Runoob', 1997, 2000, 'Google', 'Runoob', 1997, 2000)

3.3删除元组

删除不了元素,只能删除了,删除就直接释放掉了,也不用打印了,打印出错

实例:

    tup1 = ('Google', 'Runoob', 1997, 2000);
    print(tup1)
    del tup1
    print(tup1)

结果:

('Google', 'Runoob', 1997, 2000)
Traceback (most recent call last):
  File "day007.py", line 180, in <module>
    main()
  File "day007.py", line 176, in main
    print(tup1)
UnboundLocalError: local variable 'tup1' referenced before assignment

3.4 元组的一些操作,包括运算符,索引,截取,内置函数

3.4.1元组运算符

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式 结果 描述
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print (x,) 1 2 3 迭代
3.4.2 元组索引,截取

就是通过[]来实现

L = ('Google', 'Taobao', 'Runoob')
Python表达式 结果 描述
L[2] 'Runoob' 读取第三个元素
L[-2] 'Taobao' 反向读取;读取倒数第二个元素
L[1:] ('Taobao', 'Runoob') 截取元素,从第二个开始后的所有元素。
3.4.3元组的内置函数

就下面这几个

  • len(tuple)
    计算元组元素个数。

实例:

    tuple1 = ('Google', 'Runoob', 'Taobao')
    print(len(tuple1))

结果:

3
  • max(tuple)
    返回元组中元素最大值。不能有str和int 混合,不然会报错

实例:

    tuple2 = ('5', '4', '8')
    print(max(tuple2))

结果:

8
  • min(tuple)
    返回元组中元素最小值。不能有str和int 混合,不然会报错

实例:

    tuple2 = ('5', '4', '8')
    min(tuple2)

结果:

4
  • tuple(seq)
    将列表转换为元组。这个和那个list是个你过程

实例:

    list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] 
    tuple1=tuple(list1)
    print(tuple1)

结果:

('Google', 'Taobao', 'Runoob', 'Baidu')

4.字典

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

联想下map

4.1这里主要了解下操作,跟上面一样,增删改查

4.1.1访问字典里的值--

通过[]里面加key的方式访问

实例:

    dict1 = {'name': 'jinxx', 123: 345, 444: 'xxx'}
    print(dict1)
    print('dict1[list(dict1.keys())[0]] :', dict1[list(dict1.keys())[0]])  # 这个地方很好玩,拿到dict1的所有key转换为list的第一个元素做为key的dict1的value
    print('name:', dict1['name'])

结果:

{'name': 'jinxx', 123: 345, 444: 'xxx'}
dict1[list(dict1.keys())[0]] : jinxx
name: jinxx

就这么玩的,操作不存在的key会抛异常,慎重,但是可以赋值,赋值的话就是新增了

4.1.2 修改字典-- 增和改

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对

如下实例:

   dict1 = {'name': 'jinxx', 123: 345, 444: 'xxx'}
    print(dict1)
    dict1['name'] = 'liuxxx'
    print(dict1)
    dict1['age'] = 26
    print(dict1)

结果:

{'name': 'jinxx', 123: 345, 444: 'xxx'}
{'name': 'liuxxx', 123: 345, 444: 'xxx'}
{'name': 'liuxxx', 123: 345, 444: 'xxx', 'age': 26}

就这么简单

4.1.3 删除字典元素 --

可以用delclearpoppopitem

直接看实例:

    dict1 = {'name': 'jinxx', 123: 345, 444: 'xxx', 555: 5555, 'xxx': 444}
    print(dict1)
    del dict1[444]
    print('del dict1[444]:', dict1)
    dict1.pop('xxx')
    print('dict1.pop(\'xxx\')', dict1)
    dict1.popitem()
    print('dict1.popitem():', dict1)
    dict1.clear()
    print('dict1.clear()', dict1)

结果:

{'name': 'jinxx', 123: 345, 444: 'xxx', 555: 5555, 'xxx': 444}
del dict1[444]: {'name': 'jinxx', 123: 345, 555: 5555, 'xxx': 444}
dict1.pop('xxx') {'name': 'jinxx', 123: 345, 555: 5555}
dict1.popitem(): {'name': 'jinxx', 123: 345}
dict1.clear() {}

4.2字典的2个特征

4.2.1不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,

实例:

dic1 = {111: 222, '0000': '1111', 111: 3333}
print(dic1[111])

结果:

3333
4.2.2键(key)必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,用了就给你抛异常

实例:

dict2 = {(123, 456): 'abc'}
print('dict2 :', dict2)
dict3 = {[123, 456]: 'abc'}
print('dict3', dict3)

结果:

dict2 : {(123, 456): 'abc'}
    dict3 = {[123, 456]: 'abc'}
TypeError: unhashable type: 'list'

就是这个list是可变的算不出来hash值

4.3 字典内置函数&方法

4.3.1内置函数主要包括一下三个
  • len(dict) 计算字典元素个数,即键的总数。
  • str(dict) 输出字典,以可打印的字符串表示。
  • type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。

实例:

dic1 = {111: 222, '0000': '1111', 111: 3333}
print('len(dic1)', len(dic1))
print('str(dic1)', str(dic1))
print('type(dic1)', type(dic1))

结果:

len(dic1) 2
str(dic1) {111: 3333, '0000': '1111'}
type(dic1) <class 'dict'>

str()函数还排了个小序

4.3.2 Python字典包含了以下内置方法:
函数 描述
radiansdict.clear() 删除字典内所有元素
radiansdict.copy() 返回一个字典的浅复制
radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值
key in dict 如果键在字典dict里返回true,否则返回false
radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组
radiansdict.keys() 返回一个迭代器,可以使用 list() 来转换为列表
radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里
radiansdict.values() 返回一个迭代器,可以使用 list() 来转换为列表
pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
popitem() 随机返回并删除字典中的一对键和值(一般删除末尾对)。

实例操作一波

dic1 = {111: 222, '0000': '1111', 111: 3333}
dict2 = dic1.copy()
print('copy:', dict2)

tup1 = (1, 2, 3, 4, 5)
dict3 = {}
dict3 = dict3.fromkeys(tup1, 'tup')
print('fromkeys(tup1, \'tup\'):',dict3)
list1 = [4, 3, 2, 1,5,6,8]
dict4 = {}
dict4 = dict4.fromkeys(list1, 'list')
print('fromkeys(list1, \'list\'):', dict4)

print('dict4.get(4):', dict4.get(4))
print('dict4.get(100):', dict4.get(100))
print('dict4.get(100, \'nop\'):', dict4.get(100, 'nop'))

if 100 not in dict4:
    print('100  not in dict4')
if 1 in dict4:
    print('1 in dict4')

print('dict4.items():', dict4.items())

print('dict4.keys():', dict4.keys())
print('lsit(dict4.keys()):', list(dict4.keys()))

print('dict4.setdefault(3,\'default\'):', dict4.setdefault(3, 'default'))
print('dict4.setdefault(100,\'default\'):', dict4.setdefault(100, 'default'))

dict4.update(dict3)
print('dict4.update(dict3)', dict4)

print('dict4.values():', dict4.values())
print('list(dict4.values())', list(dict4.values()))

dict4.pop(100)
print('dict4.pop():', dict4)

dict4.popitem()
print('dict4.popitem()', dict4)

dict4.clear()
print('dict4.clear()', dict4)

**结果: **

copy: {111: 3333, '0000': '1111'}
fromkeys(tup1, 'tup'): {1: 'tup', 2: 'tup', 3: 'tup', 4: 'tup', 5: 'tup'}
fromkeys(list1, 'list'): {4: 'list', 3: 'list', 2: 'list', 1: 'list', 5: 'list', 6: 'list', 8: 'list'}
dict4.get(4): list
dict4.get(100): None
dict4.get(100, 'nop'): nop
100  not in dict4
1 in dict4
dict4.items(): dict_items([(4, 'list'), (3, 'list'), (2, 'list'), (1, 'list'), (5, 'list'), (6, 'list'), (8, 'list')])
dict4.keys(): dict_keys([4, 3, 2, 1, 5, 6, 8])
lsit(dict4.keys()): [4, 3, 2, 1, 5, 6, 8]
dict4.setdefault(3,'default'): list
dict4.setdefault(100,'default'): default
dict4.update(dict3) {4: 'tup', 3: 'tup', 2: 'tup', 1: 'tup', 5: 'tup', 6: 'list', 8: 'list', 100: 'default'}
dict4.values(): dict_values(['tup', 'tup', 'tup', 'tup', 'tup', 'list', 'list', 'default'])
list(dict4.values()) ['tup', 'tup', 'tup', 'tup', 'tup', 'list', 'list', 'default']
dict4.pop(): {4: 'tup', 3: 'tup', 2: 'tup', 1: 'tup', 5: 'tup', 6: 'list', 8: 'list'}
dict4.popitem() {4: 'tup', 3: 'tup', 2: 'tup', 1: 'tup', 5: 'tup', 6: 'list'}
dict4.clear() {}

有点多,哈啊哈

5 集合

集合(set)是一个无序的不重复元素序列。

可以使用大括号{ } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

创建格式:

parame = {value01,value02,...}
# 或者
set(value)

集合支持数学运算
而且可以进行交集 &、并集 |、差集 -对称差 ^运算。

实例:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print('type(basket):', type(basket))
print('basket:', basket)
print('\'orange\' in basket:', 'orange' in basket)
print('\'abc\' in basket:', 'abc' in basket)

a = {1, 2, 3, 4}
b = {4, 5, 6, 7}
print('a-b:', a-b)
print('a|b:', a|b)
print('a&b:', a&b)
print('a^b:', a^b)

**结果: **

type(basket): <class 'set'>
basket: {'banana', 'pear', 'orange', 'apple'}
'orange' in basket: True
'abc' in basket: False
a-b: {1, 2, 3}
a|b: {1, 2, 3, 4, 5, 6, 7}
a&b: {4}
a^b: {1, 2, 3, 5, 6, 7}

自动去重去掉一个orange,用in可以判断是否包含

5.1集合的一些基操

5.1.1添加元素

添加元素可以使用addupdate

  • add() 除了list都可以,使用list会报错,unhashable的错误
  • update() 必须得是迭代器iterable才行,intfloat都不行

看实例吧:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print('basket:', basket)
basket.add((1, 2))
print(basket)
basket.add(123)
print(basket)
# basket.add([123, 456])
# print(basket) # TypeError: unhashable type: 'list'
basket.update('333', (123, 456), ['list1', 'list2'])
print(basket)

结果:

basket: {'pear', 'orange', 'banana', 'apple'}
{(1, 2), 'orange', 'banana', 'pear', 'apple'}
{(1, 2), 'orange', 'banana', 'pear', 123, 'apple'}
{(1, 2), 'orange', 'banana', 456, '3', 'list2', 'pear', 123, 'list1', 'apple'}
5.1.2删除元素

主要有3种方式

  • remove() 这个删除指定元素,没有得话会报错,慎用
  • discard() 这个随意,不会报错
  • pop() 这个不管啥,出第一个,然鹅并不能出空的,会报错KeyError: 'pop from an empty set

看实例吧:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
basket.remove('pear')
print(basket)
basket.discard('apple')
print(basket)
basket.pop()
print(basket)
basket.pop()
print(basket)
basket.pop()
print(basket)

结果:

{'apple', 'pear', 'banana', 'orange'}
{'apple', 'banana', 'orange'}
{'banana', 'orange'}
{'orange'}
set()
Traceback (most recent call last):
  File "day007_home.py", line 95, in <module>
    basket.pop()
KeyError: 'pop from an empty set'

加个len()判断就不会扑空

5.1.3 len()判断长度,就这么简单

实例:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(len(basket))

结果:

4
5.1.4 x in set 判断元素是否在集合中

实例:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print('basket:', basket)
print('\'orange\' in basket:', 'orange' in basket)
print('\'abc\' in basket:', 'abc' in basket)

结果:

basket: {'orange', 'banana', 'apple', 'pear'}
'orange' in basket: True
'abc' in basket: False

5.1.5 内置的一些函数
方法 描述
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 返回集合的交集。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
pop() 随机移除元素
remove() 移除指定元素
symmetric_difference() 返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。
union() 返回两个集合的并集
update() 给集合添加元素

直接上实例就是咯:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print('basket:', basket)
basket.add(123)
print(basket)
basket1 = basket.copy()
print(basket1)
a = {1, 2, 3, 4, 'a'}
b = {3, 4, 6, 7 , 'a'}
print(a.difference(b,basket))
a.difference_update(b)
print(a)
a = {1, 2, 3, 4}
a.discard(3)
print(a)
print(a.intersection(b))
a.intersection_update(b)
print(a)
a = {1, 2, 3, 4}
b = {1, 2, 3, 4, 5, 7}
x = a.isdisjoint(b)
print(x)  # 奇怪
print(a.issubset(b))
print(a.issuperset(b))
a.pop()
print(a)
b.remove(1)
print(b)
print(a.symmetric_difference(b))
a.symmetric_difference_update(b)
print(a)
a = {1, 2, 3, 4}
print(a.union(b))
a.update('123', (8, 9), ['lsit1','list2'])
print(a)
a = {1, 2, 3, 4}
a.update({'123'}, (8, 9), ['lsit1','list2'])
print(a)
a.clear()
print(a)

结果:

basket: {'banana', 'pear', 'apple', 'orange'}
{'pear', 'banana', 123, 'apple', 'orange'}
{'banana', 123, 'pear', 'apple', 'orange'}
{1, 2}
{1, 2}
{1, 2, 4}
{4}
{4}
False
True
False
{2, 3, 4}
{2, 3, 4, 5, 7}
{5, 7}
{5, 7}
{1, 2, 3, 4, 5, 7}
{'3', 1, 2, 3, 4, '2', 'lsit1', 8, 9, '1', 'list2'}
{1, 2, 3, 4, 8, 9, '123', 'lsit1', 'list2'}
set()

这篇写了好多行。。。。打完收工,睡大觉

文集传送门 学习python100天


整个学习python100天的目录传送门


无敌分割线


再最后面附上大神的链接传送门

相关文章

  • day-007--字符串和常用数据结构

    字符串和常用数据结构 这个地方得好好看,正常得就是在操作字符串和这些类型的使用 1.字符串一些操作 字符串操作 下...

  • Python最常用的数据结构6种

    Python最常用的数据结构6种:数字、字符串、列表、元组、字典和集合。其中最为常用的是数字、字符串、列表和字典。...

  • ElasticSearch 常用数据结构

    ElasticSearch 常用数据结构 字符串类型 字符串类型:是ES最常用的类型之一。其内部使用了倒排索引算...

  • python 入门之数据类型

    常用数据结构 Number(数字) String(字符串) List(列表) Tuple(元组) Set(集合) ...

  • 字符串 元组 列表 字典

    字符串和常用数据结构 使用字符串 所谓字符串,就是由零个或多个字符组成的有限序列。在Python程序中,如果我们把...

  • Redis外部数据结构与内部数据结构

    外部数据结构与内部数据结构 外部数据结构除了常用的5种:字符串String,哈希表Hash,列表List,集合Se...

  • Redis基础知识

    1.Redis核心数据结构 1.1 String 字符串常用操作SET key value ...

  • Redis核心数据结构

    Redis存储类型 redis底层提供了5种数据结构:字符串、哈希、列表、集合、有序集合 字符串String 常用...

  • redis02--数据结构

    常用命令 String:字符串 list/set/hash/zset 这四种数据结构是容器型数据结构,它们共享下面...

  • 序列

    python中最基本的数据结构是序列,序列中最常用的是列表和元组,此外还有字符串,buffer对象,xrange对...

网友评论

    本文标题:day-007--字符串和常用数据结构

    本文链接:https://www.haomeiwen.com/subject/cvxhkctx.html