list | string | tuple | dict | set | |
构造 | d1={1} d2=dict(a=”ok”,b=2) 关键字 d3=dict([(“z”,5),(“e”,6)]) 映射 d4=dict.fromkeys(“abc”,1) m={“p”:4, ”h”:9} d5=dict(zip(m.keys(),m.values())) | #工厂函数 li=[1,2] s1=set(li) s1={1,9,3,7,5,6} | |||
删除 | |||||
修改 | |||||
函数 方法 | len(list1) max/min() reverse() 反向列表中元素 sort() 排序 clear()清空 remove(2)删除指定元素 pop() insert(2,”ppx”) append() count() list1.extend(list2) index(“a”)查找第一个匹配值的索引 remove()第一个匹配值 | replace(“”,””) split(“ ”)使用空格分割 strip(“x”)删除字符两边的遇到的第一个x,被阻则停 count(“o”,0,20) find(“1”) 返回子串所在位置的最左端索引 -1为没找到 “-”.join(list1)用指定形式连接字符串 lower() translate() 同时进行多个转换,需要转换表 | len() count(2)统计出现次数 index(2)获得指定元素的最小索引 | clear() keys() values() items() get()返回指定键的值 pop()删除指定键值 setdefault()添加键 copy()浅拷贝 fromkeys() update() | add() |
水仙花数
# 水仙花
x=int(input("x(请输入一个百位数的数字)= "))
i==x//100
j==x%100
num ==(x%100)%10
if i**3+j**2+num**2 ==x:
print("This is a flower number")
else:
print("no")
print("over")
九九乘法表
1.
i=1
while i<10:
j=1
while j<10:
if i >=j:
print(str(j)+"*"+str(i)+"="+str(i*j),end=" ")
# res = "%d*%d=%d"%(j,i,i*j)
# print=(res,end=" ")
j+=1
print("")
i+=1
2.set
for x in range(1,10):
for j in range(1,10):
if x>=j:
#zzz=str(j)+"*"+str(x)+"="+str(x*j)
print("%d*%d=%-2.d "%(j,x,x*j),end=" ")
print("")
查找
1.
import urllib.request
def find11():
s="""
xxxxxxx
"""
sub1 = "https://"
sub2 = ".jpg"
tou = 0
wei = 0
i = 0
while i < s.count(sub1):
tou = s.find(sub1, wei)
wei = s.find(sub2, tou)
dns = s[tou:wei+len(sub2)]
if len(dns)< 100:
print(dns)
urllib.request.urlretrieve(dns, "E:\\workPy\\%d.jpg"%(i))
i+=1
2.
def myFind(s,sub,start=0,end=10):
i=start
if sub in s[start:end]:
while i <end:
if s[i:i+len(sub)] == sub:
print(i)
i+=1
print("over")
print("")
else:
print(-1,"sorry")
s="abcdeabcde"
sub="bcd"
# print(myFind(s,sub))
myFind(s,sub)
chr用法
i=0
s=""
while i <26:
s+= chr(97+i)+str(i+1)
i+=1
print(s)
guess game
import random
num = 7
i=0
while i<3:
guess= random.randint(0,10)#随机生成一个数,可能是1和10,(range(0,100),10)
if guess==num:
print("Very good!")
elif guess>num:
print("The number is big.")
else:
print("The number is small.")
i+=1
print(" ")
print("Game is over!")
#range(-200,200,40)从-200开始,到200结束,以40为步长的序列
#range(5): 0,1,2,3,4
#range(1,5):1,2,3,4
查找
movie_data = """
1::Toy Story (1995)::Animation|Children's|Comedy
2::Jumanji (1995)::Adventure|Children's|Fantasy
3::Grumpier Old Men (1995)::Comedy|Romance
4::Waiting to Exhale (1995)::Comedy|Drama
"""
movies = {}
for line in movie_data.strip().split('\n'):
movie_id, title, genres = line.strip().split('::')
movies[title] = {'year': int(title[-5:-1]), 'genres': list(genres.split('|'))}
year = int(input("请输入年份: "))
genre = input("请输入类型: ")
found_movies=[]
for title, info in movies.items():
if info['year'] == year and genre in info['genres']:
found_movies.append(title)
if found_movies:
print(f"{year}年, {genre}类型的电影有:")
for movie in found_movies:
print(movie.split("(")[0]+",")
else:
print("未找到符合条件的电影.")
map,filter
li1=list(filter(lambda x: x%2==0,range(0,11)))
li2=map(lambda y:y**2,li1)
print(list(li2))
递归
1,2,6,24,120...
x=1
x=x*i (i=123456.....)
def jie(n):
i=1
res=1
while i <=n:
res=res*i
i+=1
print(res)
def jie2(n):
if n==0:
return 1
else:
return n*jie2(n-1)
#谢尔宾斯曲线
斐波那契数列、兔子
1,1,2,3,5,8,11,19......
1.
def fab1(n):
if n==1 or n==2:
return 1
else:
return fab1(n-1)+fab1(n-2)
----------------------------------------------
def jie(n):
if n<=2:
return 1
while n >2:
return jie(n-1)+jie(n-2)#就是不管了
print(jie(3))
2.
def fab2(n):
t1=1
t2=1
t2=1
while n-2>0:
t3=t1+t2
t1=t2
t2=t3
return t3
汉诺塔
cc=1
def han(n,a,b,c):
global cc
if n==1:
print(cc,":",a,"--------->",c)
cc +=1
else:
han(n-1,a,c,b)
han(1,a,b,c)
han(n-1,b,a,c)
han(3,"A","B","C")
一些用法(乱)
list
today=[1,9,"xsx",False]
print(type(today))
p=[1,2]
p.append([9,6])
[1, 2, [9, 6]]
p.extend([9,6])
[1, 2, 9, 6]
li=[1,2,9,63,8,2,6,2,8,7,2]
tou=0
while tou<len(li): #因为Index查找第一个匹配值
tou=li.index(2)
del li[tou]
print(li)
s="hello eveyone"
p=s.count(" ")
print(f"空格有{p}个")
x=10
def change():
global x #因为下面更改了x
print(x)
x=2
print(x)
change()
print(x)
10
2
2
str
s="njhndjc"
print(li1[:6])
%,format格式化
%
print"模板" %操作符 context()是元组
print("%d*%d=%d"%(y,x,x*y), end=" ")
为什么用:error:xx和xx不能。。。
print'My age is %d'% 8
数量对应、格式对应,相当于失去特性
前模板
%[(name)][flags][width].[precision]typecode
[flags][width].[precision]
km.n
%s 字符串
%c 单个字符或ASCII
$d 十进制整数
format
”i am {}, age {}, {}“.format ("", , "")
括号里直接内容如上,括号里是元组,前加一个*,是字典,**
列表,字典解析式
列表解析
生成 list=[(i+2)**2 for i in range(10)]
条件子句 [i for i in range(20) if i %2 ==0](偶数)
[i for i in range(20) if i %2==0 and i%3==0]
if在for前,必须加上else
if在for后,不能加else
字典解析
{k:v for k,v in [(),(),()]}
{x:(x,x+1) for x in range(5)}
{x:[x,x+1] for x in range(5)}
方法合集
map
filter
range
random.randiant
urllib.request.urlretrieve
copy
zip
index
find
slice切片
count
split分割