被python折磨的第三天

2019.8.16
字符串和常用数据结构

一、字符串:
就是由〇个或多个字符组成的有限序列,一般记为
s = a 1 a 2 … a n ( 0 ≤ n ≤ ∞ ) {\displaystyle s=a_{1}a_{2}\dots a_{n}(0\leq n \leq \infty)} s=a1a2an(0n)
二、字符串的使用
1.通过len函数计算字符串的长度

str = 'I love python!'
print(len(str1))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
14
  1. 获得字符串首字母大写的拷贝
str = 'hello world!'
print(str.capitalize())

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
Hello world!
  1. 获得字符串变大写后的拷贝
str = 'hello world!'
print(str1.upper())  

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
HELLO WORLD!
  1. 从字符串中查找子串所在位置
str = 'TFBOYS are my idols!'
print(str.find('BOY'))
print(str.find('boy'))     #字符串'boy'不在str中,返回值为-1
# 与find类似但找不到子串时会引发异常
print(str.index('BOY'))
print(str.index('boy'))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
2
-1
2
Traceback (most recent call last):
  File "d:/VScode/Untitled-Wed01.py", line 5, in <module>
    print(str.index('boy'))
ValueError: substring not found
  1. 检查字符串是否以指定的字符串开头
str = 'TFBOYS are my idols!'
print(str.startswith('TF'))  
print(str.startswith('tf'))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
True
False

6.检查字符串是否以指定的字符串结尾

str = 'TFBOYS are my idols!'
print(str.endswith('!'))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
True
  1. 将字符串以指定的宽度居中并在两侧填充指定的字符
str = 'TFBOYS are my idols!'
print(str.center(30, '~'))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
~~~~~TFBOYS are my idols!~~~~~~
  1. 将字符串以指定的宽度靠右放置左侧填充指定的字符
str = 'TFBOYS are my idols!'
print(str.rjust(30, ' '))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
           TFBOYS are my idols!
  1. 从字符串中取出指定位置的字符(下标运算)
str = 'siyecao2023'
print(str[2])

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
y
  1. 字符串切片(从指定的开始索引到指定的结束索引)
str = 'siyecao and tfboys 2023'
print(str[2:5]) 
print(str[5:])  
print(str[2::2]) 
print(str[::2])  
print(str[::-1]) 
print(str[-3:-1]) 

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
yec
ao and tfboys 2023
ycoadtby 03
sycoadtby 03
3202 syobft dna oaceyis
02
  1. 检查字符串是否由数字构成
str = 'siyecao and tfboys 2023'
print(str.isdigit())

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
False
  1. 检查字符串是否以字母构成
str = 'siyecao and tfboys 2023'
print(str.isalpha())

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
False
  1. 检查字符串是否以数字和字母构成
str = 'siyecao2023'    #若字符串中有空格返回值为False
print(str.isalnum())

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed01.py
True
  1. 获得字符串修剪左右两侧空格的拷贝
str = '  jackfrued@126.com '
print(str.strip())     #删除两侧空格
print(str.lstrip())	   #删除左侧空格
print(str.rstrip())	   #删除右侧空格

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
jackfrued@126.com
jackfrued@126.com
  jackfrued@126.com

15.split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print(str.split( ))        		#以空格为分隔符,包含 \n
print(str.split(' ', 1 ))  		#以空格为分隔符,分隔成两个

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

三、使用列表
列表可以进行加法,乘法
1.定义列表

list = ['hello'] * 5          #重复输出5次
print(list)
list1 = [1, 3, 5]
list2 = [2, 5, 8]
print(list1 + list2)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['hello', 'hello', 'hello', 'hello', 'hello']
[1, 3, 5, 2, 5, 8]

2.计算列表长度(元素个数)

list1 = [1, 3, 5, 7, 100]
print(len(list1))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
5

3.下标(索引)运算

list1 = [1, 3, 5, 7, 100]
print(list1[0])
print(list1[4])
print(list1[5])    #IndexError: list index out of range

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
1
100

4.添加元素

list1 = [1, 3, 5, 7, 100]
list1[2] = 300   		 #[1, 3, 300, 7 ,100]
list1.append(200)
print(list1)             #[1, 3, 300, 7 ,100 ,200]

5.删除元素

list1 = [1, 3, 5, 7, 100]
list1.remove(3)
print(list1)
#del list1[0]     //删除列表元素[5, 7, 100]

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
[1, 5, 7, 100]

6.清空列表元素

list1 = [1, 3, 5, 7, 100]
list1.clear()
print(list1)      //[]

7.循环遍历列表元素

fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'blueberry']
for fruit in fruits:
    print(fruit.title(),end=' ')#返回"标题化"的字符串,就是说所有单词都是以大写开始
print()       #空行

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
Grape Apple Strawberry Waxberry Blueberry

8.列表切片

fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'blueberry']
fruits1 = fruits[1:4]
print(fruits1)
fruits2 = fruits[-3:-1]
print(fruits2)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['apple', 'strawberry', 'waxberry']
['strawberry', 'waxberry']

9.通过反向切片操作来获得倒转后的列表的拷贝

fruits = ['grape', 'apple', 'strawberry', 'waxberry', 'blueberry']
fruits1 = fruits[::-1]
print(fruits1)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['blueberry', 'waxberry', 'strawberry', 'apple', 'grape']

10.sorted函数(默认升序)

list1 = ['grape', 'apple', 'strawberry', 'waxberry', 'blueberry']
list2 = sorted(list1)
list3 = sorted(list1, reverse=True)       #reverse逆序(翻转)
#通过key关键字参数指定根据字符串长度进行排序而不是默认的字母表顺序
list4 = sorted(list1, key=len)
print(list2)
print(list3)
print(list4)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['apple', 'blueberry', 'grape', 'strawberry', 'waxberry']
['waxberry', 'strawberry', 'grape', 'blueberry', 'apple']
['grape', 'apple', 'waxberry', 'blueberry', 'strawberry']

11.给列表对象发出排序消息直接在列表对象上进行排序

list1 = ['grape', 'apple', 'strawberry', 'waxberry', 'blueberry']
list1.sort()
#list1.sort(reverse=True)
print(list1)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['apple', 'blueberry', 'grape', 'strawberry', 'waxberry']

12.查看对象占用内存的字节数

import sys
f = [x for x in range(100) if x % 2 == 0]
print(sys.getsizeof(f))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
528

13.遍历列表

a = [x for x in range (10)]
# x :输出值       //[0,1,2,3,4,5,6,7,8,9]
b = [x for x in range (10) if x % 2 == 0]
# [0,2,4,6,8]
c = [[x, y] for x in range(3) for y in range (3)]
#[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]

四、使用元组
1.定义元组

t = ('骆昊', 38, True, '四川成都')
print(t)           #('骆昊', 38, True, '四川成都')

2.获取元组中的元素

t = ('骆昊', 38, True, '四川成都')
print(t[0])
print(t[3])

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
骆昊
四川成都

3.遍历元组中的值

t = ('骆昊', 38, True, '四川成都')
for member in t:
    print(member)

骆昊
38
True
四川成都

4.重新给元组赋值

t = ('骆昊', 38, True, '四川成都')
t[0] = '王大锤'   #TypeError
  1. 将元组转换成列表
t = ('王大锤', 20, True, '云南昆明')
person = list(t)
print(person)
# 修改它的元素
person[0] = '李小龙'
person[1] = 25
print(person)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
['王大锤', 20, True, '云南昆明']
['李小龙', 25, True, '云南昆明']

6.将列表转换成元组

fruits_list = ['apple', 'banana', 'orange']
fruits_tuple = tuple(fruits_list)
print(fruits_tuple)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
('apple', 'banana', 'orange')

五、列表与元组的区别

  1. 列表中的元素是可以修改的,可以对元素进行添加、删除、修改。而元组中的元素是无法修改的,如果不需要对元素进行添加、删除、修改的时候,可以考虑使用元组,当然如果一个方法要返回多个值,使用元组也是不错的选择。
  2. 元组在创建时间和占用的空间上面都优于列表。我们可以使用sys模块的getsizeof函数来检查存储同样的元素的元组和列表各自占用了多少内存空间,这个很容易做到。我们也可以在ipython中使用魔法指令%timeit来分析创建同样内容的元组和列表所花费的时间

六、使用集合
Python中的集合跟数学上的集合是一致的,不允许有重复元素,而且可以进行交集、并集、差集等运算。集合具有无序性
1.定义集合(set)

set1 = {1, 2, 3, 3, 3, 2}
print(set1)         			#{1,2,3}
print('Length =', len(set1))    #3为长度
set1.add(4)
set1.add(5)       				#添加元素  {1,2,3,4,5}
set1.update([11, 12])    		#添加多个元素  {1,2,3,4,5,11,12}
set2.discard(5)     			#移除指定的集合元素 {1,2,3,4,11,12}

2.遍历集合容器

set1 = {1, 2, 3, 3, 3, 2}
for elem in set1:
    print(elem ** 2, end=' ')
print()

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
1 4 9

3.移除元素

set1 = {1, 2, 3, 3, 3, 2}
if 4 in set1:
    set1.remove(4)
print(set1)
# remove的元素如果不存在会引发KeyError

4.将元组转换成集合

set3 = set((1, 2, 3, 3, 2, 1))
print(set3.pop())      #随机删除集合中的一个元素
print(set3)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
1
{2, 3}

5.集合的交集、并集、差集、对称差运算

set1 = {1, 2, 3, 3, 2, 1}
set2 = {7,5,9,6,1,2}
print(set1 & set2)
# print(set1.intersection(set2))
print(set1 | set2)
# print(set1.union(set2))
print(set1 - set2)
# print(set1.difference(set2))
print(set1 ^ set2)     #不存在的元素生成一个集合
# print(set1.symmetric_difference(set2))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
{1, 2}
{1, 2, 3, 5, 6, 7, 9}
{3}
{3, 5, 6, 7, 9}

6.判断子集和超集

set1 = {1, 2, 3, 3, 2, 1}
set2 = {1,2}
print(set2 <= set1)
# print(set2.issubset(set1))
print(set1 >= set2)
# print(set1.issuperset(set2))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
True
True

七、使用字典
字典是另一种可变容器模型,它可以存储任意类型对象,与列表、集合不同的是,字典的每个元素都是由一个键和一个值组成的“键值对”,键和值通过冒号分开。
注意:字典的一切操作都是通过键名操作键值!!!
字典是无序的,没有索引操作,除非转换成有序字典,

1.定义字典

scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
#通过键可以获取字典中对应的值
print(scores['骆昊'])       #95
print(scores['狄仁杰'])     #82

2.对字典进行遍历(遍历的其实是键再通过键取对应的值)

scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
for elem in scores:
    print('%s\t--->\t%d' % (elem, scores[elem]))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
骆昊    --->    95
白元芳  --->    78
狄仁杰  --->    82

3.更新字典中的元素

scores = {'骆昊': 95, '白元芳': 78, '狄仁杰': 82}
scores['白元芳'] = 65
scores['诸葛王朗'] = 71
scores.update(冷面=67, 方启鹤=85)
print(scores)

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
{'骆昊': 95, '白元芳': 65, '狄仁杰': 82, '诸葛王朗': 71, '冷面': 67, '方启鹤': 85}

4.删除字典中的元素

scores = {'骆昊':100, '白元芳': 78, '狄仁杰': 82}
print(scores.popitem())
print(scores.popitem())
print(scores.pop('骆昊', 100))

(base) C:\Users\Administrator>F:/install/Anaconda/python.exe d:/VScode/Untitled-Wed02.py
('狄仁杰', 82)
('白元芳', 78)
100

5.清空字典

scores.clear()
  1. 同时获取键值对
dict_ = {1:100,'Joker':'value'}
for key,value in dict_.items():
    print(key,value)

7.获取键名,获取键值

dict_ = {1:100,'Joker':'value'}
print(dict_.keys())
print(dict_.values())

补充:

匿名函数格式:

lambda x,y :print(x,y)(100,10)
#  自变量         应变量
day01.py
  def A():
  	print('hahaha')
  	print(_name_)
  	if _name_ = '_main_'
  A()
day02.py
  from day01 import *       #导入所有内容
  A()

课堂习题
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值