python基础之容器

python基础之容器

字符串

单引号或者双引号或者三引号中的数据,就是字符串

    b = "hello itcast.cn"
    或者
    b = 'hello itcast.cn'
    或者
    b = '''hello itcast.cn'''
    或者
    b = """hello itcast.cn"""

字符串输出

格式化操作符(%s)
    name = '王富国'
    position = '讲师'
    address = '北京市'

    print('--------------------------------------------------')
    print("姓名:%s" % name)
    print("职位:%s" % position)
    print("公司地址:%s" % address)
    print('--------------------------------------------------')

输出结果

    --------------------------------------------------
    姓名: 王富国
    职位: 讲师
    公司地址: 北京市
    --------------------------------------------------
f-strings

f-strings 提供一种简洁易读的方式, 可以在字符串中包含 Python 表达式. f-strings 以字母 ‘f’ 或 ‘F’ 为前缀, 格式化字符串使用一对单引号、双引号、三单引号、三双引号. 格式化字符串中

name = '王富国'
age = 33
format_string1 = f'我的名字是 {name}, 我的年龄是 {age}'
format_string2 = f"我的名字是 {name}, 我的年龄是 {age}"
format_string3 = F'''我的名字是 {name}, 我的年龄是 {age}'''
format_string4 = F"""我的名字是 {name}, 我的年龄是 {age}"""
format_string5 = f'3 + 5 = {3 + 5}'
a = 10
b = 20
format_string6 = f'3 + 5 = {a + b}'
# 两个花括号会被替换为一个花括号, 注意{{}} 不表示表达式
format_string7 = F'我的名字是 {{name}}, 我的年龄是 {{age}}'

print(format_string1)
print(format_string2)
print(format_string3)
print(format_string4)
print(format_string5)
print(format_string6)
print(format_string7)

输出结果

我的名字是 王富国, 我的年龄是 33
我的名字是 王富国, 我的年龄是 33
我的名字是 王富国, 我的年龄是 33
我的名字是 王富国, 我的年龄是 33
3 + 5 = 8
3 + 5 = 30
我的名字是 {name}, 我的年龄是 {age}
注意点

f-strings在python3.6之后的版本才能使用,包括python3.6

字符串输入

之前在学习input的时候,通过它能够完成从键盘获取数据,然后保存到指定的变量中;

注意:input获取的数据,都以字符串的方式进行保存,即使输入的是数字,那么也是以字符串方式保存

demo:

    userName = input('请输入用户名:')
    print("用户名为:%s" % userName)

    password = input('请输入密码:')
    print("密码为:%s" % password)

结果:(根据输入的不同结果也不同

    请输入用户名:itheima
    用户名为: itheima
    请输入密码:haohaoxuexitiantianxiangshang
    密码为: haohaoxuexitiantianxiangshang

下标和切片

下标索引

所谓“下标”,就是编号,就好比超市中的存储柜的编号,通过这个编号就能找到相应的存储空间

如果想取出部分字符,那么可以通过下标的方法,(注意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[0:5]) # 取 下标为0~4 的字符

运行结果:

abcde

示例3:

     name = 'abcdef'

     print(name[3:5]) # 取 下标为3、4 的字符字符

运行结果:

de

示例4:

     name = 'abcdef'

     print(name[2:]) # 取 下标为2开始到最后的字符字符

运行结果:

cdef

示例5:

     name = 'abcdef'

     print(name[1:-1]) # 取 下标为1开始 到 最后第2个  之间的字符

运行结果:

bcde

字符串常见操作

如有字符串mystr = ‘hello world itcast and itcastcpp’,以下是常见的操作

find

检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1

格式

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

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.find('itcast')
print(str1)

运行结果:

12
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.find('itcast',0,10)
print(str1)

运行结果:

-1
index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常(所以我就不详细写了)

格式

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

count

返回 str 在start和end之间 在 mystr里面出现的次数

格式

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

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.count('itcast')
print(str1)

运行结果:

2
replace

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次.

格式

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

示例1
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.replace('itcast','Itcast')
print(str1)

运行结果:

hello world Itcast and Itcastcpp
示例2(指定count)
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.replace('itcast','Itcast',1)
print(str1)

运行结果:

hello world Itcast and itcastcpp
split

以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串

格式

mystr.split(str=" ", 2)

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.split(' ')
print(str1)

运行结果:

['hello', 'world', 'itcast', 'and', 'itcastcpp']
capitalize

把字符串的第一个字符大写

格式

mystr.capitalize()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.capitalize()
print(str1)

运行结果:

Hello world itcast and itcastcpp
title

把字符串的每个单词首字母大写

格式

mystr.capitalize()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.title()
print(str1)

运行结果:

Hello World Itcast And Itcastcpp
startswith

检查字符串是否是以 hello 开头, 是则返回 True,否则返回 False

格式

mystr.startswith(hello)

示例1
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.startswith('hello')
print(str1)

运行结果:

True
示例2
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.startswith('Hello')
print(str1)

运行结果:

False
endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False.

格式

mystr.endswith(obj)

示例1
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.endswith('itcastcpp')
print(str1)

运行结果:

True
示例2
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.endswith('Itcastcpp')
print(str1)

运行结果:

False
lower

转换 mystr 中所有大写字符为小写

格式

mystr.lower()

示例
mystr = 'HELLO world itcast and itcastcpp'
str1 = mystr.lower()
print(str1)

运行结果:

hello world itcast and itcastcpp
upper

转换 mystr 中的小写字母为大写

格式

mystr.upper()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.upper()
print(str1)

运行结果:

HELLO WORLD ITCAST AND ITCASTCPP
lstrip

删除 mystr 左边的空白字符

格式

mystr.lstrip()

示例
mystr = '          hello world itcast and itcastcpp         '
str1 = mystr.lstrip()
print(str1)

运行结果:

hello world itcast and itcastcpp         
rstrip

删除 mystr 字符串末尾的空白字符

格式

mystr.rstrip()

示例
mystr = '          hello world itcast and itcastcpp         '
str1 = mystr.rstrip()
print(str1)

运行结果:

          hello world itcast and itcastcpp
strip

删除mystr字符串两端的空白字符

格式

mystr.strip()

示例
mystr = '          hello world itcast and itcastcpp         '
str1 = mystr.strip()
print(str1)

运行结果:

hello world itcast and itcastcpp
rfind

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

格式

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

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.rfind('itcast')
print(str1)

运行结果:

23
rindex

类似于 index(),不过是从右边开始.(同理,这个和上面的一样,不过是不存在就报错)

partition

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

格式

mystr.partition(str)

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.partition('itcast')
print(str1)

运行结果:

('hello world ', 'itcast', ' and itcastcpp')
rpartition

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

格式

mystr.rpartition(str)

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.rpartition('itcast')
print(str1)

运行结果:

('hello world itcast and ', 'itcast', 'cpp')
splitlines

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

格式

mystr.splitlines()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.splitlines()
print(str1)

运行结果:

['hello world itcast and itcastcpp']
isalpha

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

格式

mystr.isalpha()

示例
mystr = 'helloworlditcastanditcastcpp'
str1 = mystr.isalpha()
print(str1)

运行结果:

True
示例2
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.isalpha()
print(str1)

运行结果:

False
isdigit

如果 mystr 只包含数字则返回 True 否则返回 False.

格式

mystr.isdigit()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.isdigit()
print(str1)

运行结果:

False
isalnum

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

格式

mystr.isalnum()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.isalnum()
print(str1)

运行结果:

False

有空格所以是false

isspace

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

格式

mystr.isspace()

示例
mystr = 'hello world itcast and itcastcpp'
str1 = mystr.isspace()
print(str1)

运行结果:

False
join

mystr 中每个元素后面插入str,构造出一个新的字符串

格式

mystr.join(str)

示例
mystr = ' '
li = ['hello', 'world', 'itcast', 'and', 'itcastcpp']
str1 = mystr.join(li)
print(str1)

运行结果:

hello world itcast and itcastcpp

列表

用于存储多个数据

列表的格式

namesList = [‘xiaoWang’,‘xiaoZhang’,‘xiaoHua’]

打印列表

    namesList = ['xiaoWang','xiaoZhang','xiaoHua']
    print(namesList[0])
    print(namesList[1])
    print(namesList[2])

运行结果:

    xiaoWang
    xiaoZhang
    xiaoHua
列表的循环遍历

为了更有效率的输出列表的每个数据,可以使用循环来完成

使用for循环
namesList = ['xiaoWang','xiaoZhang','xiaoHua']
    for name in namesList:
        print(name)

运行结果:

    xiaoWang
    xiaoZhang
    xiaoHua
使用while循环
    namesList = ['xiaoWang','xiaoZhang','xiaoHua']

    length = len(namesList)

    i = 0

    while i<length:
        print(namesList[i])
        i+=1

运行结果:

    xiaoWang
    xiaoZhang
    xiaoHua
列表的相关操作
添加元素("增"append, extend, insert)
append
# 定义变量A,默认有3个元素
A = ['xiaoWang']

print("-----添加之前,列表A的数据-----")
for tempName in A:
    print(tempName)

# 提示、并添加元素
temp = input('请输入要添加的学生姓名:')
A.append(temp)

print("-----添加之后,列表A的数据-----")
for tempName in A:
    print(tempName)

运行结果:

-----添加之前,列表A的数据-----
xiaoWang
请输入要添加的学生姓名:123
-----添加之后,列表A的数据-----
xiaoWang
123
extend

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

a = [1,2]
b = [3,4]
a.extend(b)
print(a)

运行结果:

[1, 2, 3, 4]
insert

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

a = [1,2]
a.insert(1,3)
print(a)

运行结果:

[1, 3, 2]
修改元素(“改”)

修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改

    #定义变量A,默认有3个元素
    A = ['xiaoWang','xiaoZhang','xiaoHua']

    print("-----修改之前,列表A的数据-----")
    for tempName in A:
        print(tempName)

    #修改元素
    A[1] = 'xiaoLu'

    print("-----修改之后,列表A的数据-----")
    for tempName in A:
        print(tempName)

运行结果:

    -----修改之前,列表A的数据-----
    xiaoWang
    xiaoZhang
    xiaoHua
    -----修改之后,列表A的数据-----
    xiaoWang
    xiaoLu
    xiaoHua
查找元素("查"in, not in, index, count)
in, not in

python中查找的常用方法为:

in(存在),如果存在那么结果为true,否则为false
not in(不存在),如果不存在那么结果为true,否则false
    #待查找的列表
    nameList = ['xiaoWang','xiaoZhang','xiaoHua']

    #获取用户要查找的名字
    findName = input('请输入要查找的姓名:')

    #查找是否存在
    if findName in nameList:
        print('在字典中找到了相同的名字')
    else:
        print('没有找到')

运行结果1(找到):

请输入要查找的姓名:xiaoWang
在字典中找到了相同的名字

运行结果2(没找到):

请输入要查找的姓名:x
没有找到
index, count

index和count与字符串中的用法相同
index查找没有就报错
count计数

删除元素(del, pop, remove)

类比现实生活中,如果某位同学调班了,那么就应该把这个条走后的学生的姓名删除掉;在开发中经常会用到删除这种功能。

列表元素的常用删除方法有:

del:根据下标进行删除
pop:删除最后一个元素
remove:根据元素的值进行删除
del
    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']

    print('------删除之前------')
    for tempName in movieName:
        print(tempName)

    del movieName[2]

    print('------删除之后------')
    for tempName in movieName:
        print(tempName)

运行结果:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    指环王
    霍比特人
    速度与激情
pop
    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']

    print('------删除之前------')
    for tempName in movieName:
        print(tempName)

    movieName.pop()

    print('------删除之后------')
    for tempName in movieName:
        print(tempName)

运行结果:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人

pop不指定下标默认删除最后一个

remove
    movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']

    print('------删除之前------')
    for tempName in movieName:
        print(tempName)

    movieName.remove('指环王')

    print('------删除之后------')
    for tempName in movieName:
        print(tempName)

运行结果:

    ------删除之前------
    加勒比海盗
    骇客帝国
    第一滴血
    指环王
    霍比特人
    速度与激情
    ------删除之后------
    加勒比海盗
    骇客帝国
    第一滴血
    霍比特人
    速度与激情
排序(sort, reverse)

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

reverse倒序
a = [1,5,78,4,67,467,4167,1,67]
a.reverse()
print(a)

运行结果:

[67, 1, 4167, 467, 67, 4, 78, 5, 1]
从大到小
a = [1,5,78,4,67,467,4167,1,67]
a.sort(reverse=True)
print(a)

运行结果:

[4167, 467, 78, 67, 67, 5, 4, 1, 1]
从小到大
a = [1,5,78,4,67,467,4167,1,67]
a.sort(reverse=False)
print(a)

运行结果:

[1, 1, 4, 5, 67, 67, 78, 467, 4167]
列表嵌套

类似while循环的嵌套,列表也是支持嵌套的

一个列表中的元素又是一个列表,那么这就是列表的嵌套

    schoolNames = [['北京大学','清华大学'],
                    ['南开大学','天津大学','天津师范大学'],
                    ['山东大学','中国海洋大学']]
应用

一个学校,有3个办公室,现在有8位老师等待工位的分配,请编写程序,完成随机的分配

参考答案
import random

# 定义一个列表用来保存3个办公室
offices = [[],[],[]]

# 定义一个列表用来存储8位老师的名字
names = ['A','B','C','D','E','F','G','H']

i = 0
for name in names:
    index = random.randint(0,2)    
    offices[index].append(name)

i = 1
for tempNames in offices:
    print('办公室%d的人数为:%d'%(i,len(tempNames)))
    i+=1
    for name in tempNames:
        print("%s"%name,end='')
    print("\n")
    print("-"*20)

元组

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

注意

python中不允许修改元组的数据,包括不能删除其中的元素

查找(count, index)

index和count与字符串和列表中的用法相同

count

查找数据所在下标

index

查找指定的数据,可以指定区间,数据不存在时报错

元组可以使用下标
t = ('hello','world')
print(t[1])

运行结果:

world

字典

字典和列表一样,也能够存储多个数据
列表中找某个元素时,是根据下标进行的
字典中找某个元素时,是根据'名字'(就是冒号:前面的那个值,例如上面代码中的'name'、'id'、'sex')
字典的每个元素由2部分组成,键:值。例如 'name':'班长' ,'name'为键,'班长'为值
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}

print(info['name'])
print(info['address'])

运行结果:

班长
地球亚洲中国北京

若访问不存在的键,则会报错

在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值

d1 = {'name':'lisi'}
print(d1.get('age',18))

运行结果:

18
查看元素

查看元素

    info = {'name':'吴彦祖','age':18}

    print(info['age']) # 获取年龄

    # print(info['sex']) # 获取不存在的key,会发生异常

    print(info.get('sex')) # 获取不存在的key,获取到空的内容,不会出现异常
修改元素

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

    info = {'name':'班长', 'id':100, 'sex':'f', 'address':'地球亚洲中国北京'}

    newId = input('请输入新的学号')

    info['id'] = int(newId)

    print('修改之后的id为%d:'%info['id'])

运行结果:

请输入新的学号:1
修改之后的id:1
添加元素
info = {'name': '班长', 'sex': 'f', 'address': '地球亚洲中国北京'}

# print('id为:%d'%info['id'])#程序会终端运行,因为访问了不存在的键

newId = input('请输入新的学号:')

info['id'] = newId

print(f'添加之后的id为:%d' % int(info['id']))

运行结果:

请输入新的学号:5
添加之后的id:5
删除元素

对字典进行删除操作,有一下几种:

del
clear()
del删除指定的元素
    info = {'name':'班长', 'sex':'f', 'address':'地球亚洲中国北京'}

    print('删除前,%s'%info['name'])

    del info['name']

    print('删除后,%s'%info['name'])

运行结果:

删除前,班长
Traceback (most recent call last):
  File "C:/Users/HyMas/Desktop/csdn/wda.py", line 7, in <module>
    print('删除后,%s' % info['name'])
KeyError: 'name'
删除后就没有name这个键,所以无法访问
del删除整个字典
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}

print('删除前,%s' % info)

del info

print('删除后,%s' % info)

运行结果:

删除前,{'name': 'monitor', 'sex': 'f', 'address': 'China'}
  File "C:/Users/HyMas/Desktop/csdn/wda.py", line 7, in <module>
    print('删除后,%s' % info)
NameError: name 'info' is not defined
info未定义表示以删除
clear清空整个字典
    info = {'name':'monitor', 'sex':'f', 'address':'China'}

    print('清空前,%s'%info)

    info.clear()

    print('清空后,%s'%info)

运行结果:

清空前,{'name': 'monitor', 'sex': 'f', 'address': 'China'}
清空后,{}
还有一些常见操作
len()

测量字典中,键值对的个数

keys()

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

values()

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

items()

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

字典的遍历

通过for … in … 我们可以遍历字符串、列表、元组、字典等

遍历字典的key
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
for key in info:
    print(key)

运行结果:

name
sex
address
遍历字典的value
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
for value in info.values():
    print(value)

运行结果:

monitor
f
China
遍历字典的元素
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
for item in info.items():
    print(item)

运行结果:

('name', 'monitor')
('sex', 'f')
('address', 'China')
遍历字典的键值对
info = {'name': 'monitor', 'sex': 'f', 'address': 'China'}
for key,value in info.items():
    print(key,value)

运行结果:

name monitor
sex f
address China
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值