python第五章学习笔记

序列:在python中相当于若干元素的一个容器
分类:列表:list[],元组:(),字符串,Unicode字符串,buffer对象,xrange/range对象
通用操作:
索引:按下标取值
分片:s[i:j:k]

l=[1,2,3,4,5,6,7,8,9]
print(l[1:9:1])
print(l[1:9:2])
print(l[1:9:3])

[2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]
[2, 5, 8]
加:连接两个序列

l=[1,2,3,4,5,6,7,8,9]
s=['a','b','c']
print(l+s)

[1, 2, 3, 4, 5, 6, 7, 8, 9, ‘a’, ‘b’, ‘c’]
乘:重复连接同意序列

s=['a','b','c']
print(s*3)

[‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’, ‘a’, ‘b’, ‘c’]
检查某个元素是否属于这个序列 x in l

l=[1,2,3,4,5,6,7,8,9]
print(1 in l)

True
计算序列长度 len(x)

l=[1,2,3,4,5,6,7,8,9]
print(len(l)) #9

找出最大元素和最小元素

l=[1,2,3,4,5,6,7,8,9]
print(max(l))#9
print(min(l))#1
l=[1,2,3,4,5,6,7,8,9]
print(l.index(2,1,4))#1  2:要查找的数   1:起始查找的位置  4:终止查找的位置
l=[1,2,2,2,2,6,7,8,9]
print(l.count(2))#4  计数2在l中出现的次数

字符串:
数字与字符串之间的相互转化
str(a) #数字转化为字符串
int() float()#字符串转化为数字
格式化生成字符串

n,f,s=62,5.03,'string'
print('n=%d,f=%f,s=%s'%(n,f,s))

n=62,f=5.030000,s=string
字符串操作函数:
字串查找与替换:str.find(s) str.rfind(s) str.replace(old,new)
查找子串的位置:str.index(s)
裁掉特定的字符的函数:str.lstrip([chars]) str.rstrip([chars]) str.strip([chars])

s="www.example.com"
print(s.rstrip("cmowz"))
print(s.lstrip("cmowz"))
print(s.strip("cmowz"))

www.example.
.example.com
.example.
分割字串:str.split(sep)

s="www.example.com"
print(s.split('.'))

[‘www’, ‘example’, ‘com’]
大写字母转小写:

s="ABcdf" 
print(s.lower())#abcdf

小写字母转大写:

s="abcdEFD"
print(s.upper())#ABCDEFD

分离汉语和英语

def chinese(s):
    if(ord(s)>0  and ord(s)<128):
        return False
    else:
        return True
def fen():
    l="I我am非常very善良kind"
    c=""
    e=""
    d=1
    for i in l:
        if chinese(i):
            if d==1:
                e=e+' '
                d=0
            c=c+i
        else:
            e=e+i
            if(d==0):
                d=1
    print(c)
    print(e)
fen()

我非常善良
I am very kind
输入两个字符串,求两个字符串的最长公共字串

def findl():
    a="qwerty"
    b="ertyioplm"
    m=0
    c=""
    for i in range(0,len(b)):
        for j in range(i+1,len(b)+1):
            if(b[i:j]in a and m<j-i):
                m=j-i
                c=b[i:j]
    print(c)
findl()

列表:
l=[]
l=[1,2,3]
a=10
b=“Wuji”
l=[2,‘green’,‘blue’,[a,b]]

b='Wuji'
l=list(b)
print(l)

[‘W’, ‘u’, ‘j’, ‘i’]
列表操作函数

l=[1,2]
l.append("abc")
print(l)#[1, 2, 'abc']
l.extend(["1233"])
print(l)#[1, 2, 'abc', '1233']
l.insert(1,"qwe")
print(l)#[1, 'qwe', 2, 'abc', '1233']
l.pop(1)
print(l)#[1, 2, 'abc', '1233']
l.remove('abc')
print(l)#[1, 2, '1233']
del(l[1:2])
print(l)#[1, '1233']
#列表操作函数
l=[17,3,9,2,4,4,4,4]
print(l.index(4))#4
print(l.sort())#None  注意l.sort()没有返回值
l.sort()
print(l) #[2, 3, 4, 4, 4, 4, 9, 17]
l.sort(reverse=True)
print(l)#[17, 9, 4, 4, 4, 4, 3, 2]
l=['a','b','b','c','d','b','a']
b=['b','c']
for i in l:
    if i in b:
        print(i)#注意第二个b并没有打印出来   
        l.remove(i)#删除首个符合条件的元素,所以remove不能按索引删除
print(l)
b
c
b
['a', 'd', 'b', 'a']#删除list上有多个连续的要删除的项目,会保留最后一个
l=['a','b','b','c','d','b','a']
b=['b','c']
for i in l[:]:#l[:]与l不是同一个list,相当于把l的内存拷贝到一块新的内存,当对l做remove操作时,新的内存里的列表不受影响
    if i in b:
        print(l.index(i))
        l.remove(i)
print(l)
1
1
1
2
['a', 'd', 'a']
a="This is a test string from Andres"
s=a.split()
s.sort(key=str.lower)
print(s)#['a', 'Andres', 'from', 'is', 'string', 'test', 'This']
s.clear()
print(s)#[]

判断是否为合法的ip;将每个地址段转化为二进制数,重新拼接后输出

from math import *
def pip(s):
    a=s.split('.')
    b=0
    if(len(a)!=4):
        return False
    else:
        for i in a:
            if i.isdigit()==False or (int(i)<0  or int(i)>255):
                return False
            else:
                b=b+1
        if(b==4):
            return True
def change(s):
    a=s.split('.')
    c=[]
    d=""
    for i in a:
       d=bin(int(i))
       f=d.replace('0b',"")
       while len(f)<8:
           f='0'+f
       c.append(f)
    s=""
    s=str(c[0])+'.'+str(c[1])+'.'+str(c[2])+'.'+str(c[3])
    print(s)
print(pip("008.008.008.008"))
change("008.008.008.008")

divmod(9,5)=(1,4) 1=9//5 4=9%5

from math import *
def pip(s):
    a=s.split('.')
    b=0
    if(len(a)!=4):
        return False
    else:
        for i in a:
            if i.isdigit()==False or (int(i)<0  or int(i)>255):
                return False
            else:
                b=b+1
        if(b==4):
            return True
def change(s):
    a=s.split('.')
    c=[]
    d=""
    for i in a:
     while int(i):
       i,f=divmod(int(i),2)
       d=str(f)+d
     while len(d)<8:
        d='0'+d
     c.append(d)
    s=""
    s=str(c[0])+'.'+str(c[1])+'.'+str(c[2])+'.'+str(c[3])
    print(s)
print(pip("008.008.008.008"))
change("008.008.008.008")

用列表表示多维数据

a=[]
for i in range(0,3):
    a.append([])
    for j in range(0,2):
        b=input("b=")
        a[i].append(b)
print(a)#[['1', '2'], ['3', '4'], ['5', '6']]

计算已知点的任意两点间的最大距离

from math import *
def dd(x1,x2,y1,y2):
    return sqrt((x1-x2)**2+(y1-y2)**2)
x=[1,-1,2,-2,4]
y=[2,3,1.5,0,2]
m=0
for i in range(0,len(x)):
    for j in range(0,len(y)):
        d=dd(x[i],x[j],y[i],y[j])
        print("%.2f"%d,' ',end="")
        if(d>m):
            m=d
    print()
print("%.2f"%m)

0.00 2.24 1.12 3.61 3.00
2.24 0.00 3.35 3.16 5.10
1.12 3.35 0.00 4.27 2.06
3.61 3.16 4.27 0.00 6.32
3.00 5.10 2.06 6.32 0.00
6.32
元组:
t=(1,2,3)
t=(“a”,‘b’,[1,2])
元组是固定不变的列表
字典
字典的基本操作:
创建
修改 D[key]=value
添加 D[newkey]=newvalue
删除 del D[key] D.clear

d={1:"1",2:"2",3:"3"}
del d[1]
print(d)

{2: ‘2’, 3: ‘3’}
测试元素是否在字典中 key in D
元素遍历

d={1:"1",2:"2",3:"3"}
for i in d.items():
    key,value=i
    print(key,value)
d={'a':1,'b':2,'c':3}
d.setdefault('e',4)
print(d)
k=d.keys()
print(k)
v=d.values()
print(v)
i=d.items()
print(i)
print(d.get('a'))
print(d['a'])
d.pop('c')
print(d)
d.update(f=9)
print(d)
d.update(e=6)
print(d)
{'a': 1, 'b': 2, 'c': 3, 'e': 4}
dict_keys(['a', 'b', 'c', 'e'])
dict_values([1, 2, 3, 4])
dict_items([('a', 1), ('b', 2), ('c', 3), ('e', 4)])
1
1
{'a': 1, 'b': 2, 'e': 4}
{'a': 1, 'b': 2, 'e': 4, 'f': 9}
{'a': 1, 'b': 2, 'e': 6, 'f': 9}

【例5-6】输入一段英文文字,统计其中出现的英文单词及其出现次数。要求程序可以过滤掉常见的标点符号,并按下面要求输出:
(1)将出现次数大于2的单词按字典序输出
(2)将出现次数大于2的单词按单词出现次数从大到小排序输出
[问题分析]本例的关键是分离单词,但首先要滤掉标点符号。过滤标点可以将常见标点全部 替换为空格或一种标点,然后按这种唯一的标点分离出每个单词。本例要求统计每个单 词的出现次数,可以用字典表示,单词是键,次数是值

def g(a):
    return a[1]
s="!;.,\()-:# @ "
l="I,have.have.have#apple@apple,apple,apple"
for i in s:
    if i in l:
        l=l.replace(i,',')
L=l.split(',')
a=list(set(L))
w={}
for i in L:
    if i in w:
        w[i]=w[i]+1
    else:
        w[i]=1
b=[]
for i in a:
    if w[i]>2:
        print(i,w[i])
        b.append(i)
b.sort(key=g)
print(b)

集合:
元素无序且不能重复,可变集合(set)不可变集合(Frozenset)
集合的创建

s=set(['a','b'])
print(s)#{'a', 'b'}
s={1,2,3}
print(s)#{1, 2, 3}
s={('a','b'),1,2}
print(s)#{1, ('a', 'b'), 2}

同一个集合可能输出的集合的元素的顺序与原来不同,因为集合本来就是无序的

s={i for i in range(0,10)}
print(s) #{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

添加元素:

s={('a','b'),1,2}
s.add('abc')
print(s)#{'abc', ('a', 'b'), 2, 1}
s.update([8,9,10],('e','f'),'zxd')#[8,9,10] 相当于直接向s中添加数字,()相当于直接向其中添加字符,'zxd'会被拆开,如果要添加完整的字符串要用add
print(s)#{'z', 1, 2, 8, 9, 10, 'd', 'e', 'abc', ('a', 'b'), 'x', 'f'}

删除元素:

s={('a','b'),1,2}
s.discard(1)
print(s)#{('a', 'b'), 2}
s={('a','b'),1,2}
s.remove(2)
print(s)#{1, ('a', 'b')}
s={('a','b'),1,2}
s.pop()#任意删掉集合中的一个元素
s.pop()
print(s)
s={('a','b'),1,2}
s.clear()
print(s)  #set()

s.discard(obj) s.remove(obj) 的区别在于,当obj存在于s中时,都将会被删除,但当当obj不存在于s中时,remove()会报错,discard()不会

s={('a','b'),1,2}
t={1,2}
print(t.issubset(s))#t是s的子集    True
print(s.issuperset(t))#s包含集合t    True
print(s==t)# False
print(s!=t)#True
print(s>t)  #True
print(s<t)   #False

集合的交集、并集、差集、对称差集

s={('a','b'),1,2,3}
t={1,2,4}
print(s.intersection(t))
print(s&t)
print(s.union(t))
print(s|t)
print(s.difference(t))
print(s-t)
print(s.symmetric_difference(t))# 对称差集  返回两个集合中不重复的元素
print(s^t)

{1, 2}
{1, 2}
{1, 2, 3, 4, (‘a’, ‘b’)}
{1, 2, 3, 4, (‘a’, ‘b’)}
{3, (‘a’, ‘b’)}
{3, (‘a’, ‘b’)}
{3, 4, (‘a’, ‘b’)}
{3, 4, (‘a’, ‘b’)}
迭代器:
一种对象,提供在某种容器上的遍历元素的方法
iter()返回迭代器自身的元素
next()返回容器中的下一个元素
iter(某种可以迭代的对象)

s={1,2}
i=iter(s)
try:
    while True:
        a=i.__next__()
        print(a)
except StopIteration:
    print("finish!")

1
2
finish!
生成器
生成器是一个带有yeild语句的函数,它用于产生一系列的数据

def counter(start=0):
    while True:
        yield(start)
        start+=1
g=counter(0)
print(g.__next__())#0
print(g.__next__())#1
print(g.__next__())#2
print(g.__next__())#3
def get_0_1():
    yield(0)
    yield(1)
g=get_0_1()
print(g.__next__())#0
print(g.__next__())#1

利用生成器构造一个fabonacci函数,生成小于100的数并输出

def fibonacci():
    yield(1)
    yield(1)
    a=b=1
    while True:
        a,b=b,a+b
        yield(b)
f=fibonacci()
for i in f:
     if(i<100):
        print(i,' ',end="")#1  1  2  3  5  8  13  21  34  55  89 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值