def hello():
return 'hello','word' 返回多个值
result=hello()
print(result,type(result))
a,b=('hello','word')
print(a,b)
res1,res2=hello()
print(res1,res2)
/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day01/01_python_zuoye.py
('hello', 'word') <class 'tuple'>
hello word
hello word
Process finished with exit code 0
def is_float_int(t):
for item in t:
if not isinstance(item,(int,float)): 判断字符类型
return False
else:
return True
def get_max_min_avg(*args): 元组数据类型
if is_float_int(args):
return max(args),min(args),sum(args)/len(args) 长度为个数
print(get_max_min_avg(1,2,3,2j+1))
形参的顺序:
def fun(a, a=2, *args, **kwargs)
def hello(*args,a=1,b=2):
print(args)
print(a,b)
hello(1,2,3,4,5,6,7,a=100,b=200) 可以进行这样的赋值
/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day01/01_python_zuoye.py
(1, 2, 3, 4, 5, 6, 7)
100 200
Process finished with exit code 0
形参的默认值必须为不可变类型
可变数据类型 list,set,dict
def fun(li=None): 这样写是ok的
li=[]
li.append('hello')
return li
print(fun())
print(fun())
>>> min(1,2,3,45)
1
>>> a=min 理解函数名
>>> a(1,2,3,4,5,)
1
>>> a
<built-in function min>
>>> max=min 皮一下
>>> max(1,2,3,4,5)
1
>>> a=min 功能一样
>>> id(a)
139816275492368 id指向同一个地方
>>> id(min)
139816275492368
pass 定义一个什么也不做的函数,相当于占位符,让代码能运行起来
数据类型检查可以用内置函数 isinstance 实现
默认参数一定要用不可变对象
可变参数:*arg 是不可变参数,arg接收的是一个 tuple
关键字参数:**kw是关键字参数,kw接收的是一个dict
对于任意函数,都可以通过类似 fun(*arg , **kw)的形式调用它
d=dict(a=1,b=2)
for i in d:
print(i) 查看 key 值
for i in d:
print('%s -> %s' %(i,d[i])) 查看 key-value 值
for key,value in d.items(): 查看 key-value 值
print('%s ->%s' %(key,value))
from collections import Iterable 引用模块,判断类型
a=isinstance(1,int)
b=isinstance(1,Iterable)
print(a,b)
for index,value in enumerate('hello'): 枚举法 即索引值对应元素
print(index,value)
/usr/local/python3/bin/python3.6 /root/PycharmProjects/untitled/day01/01_python_zuoye.py
0 h
1 e
2 l
3 l
4 o
Process finished with exit code 0
随机生成100个1-255的ip
import random
import pprint
ips=[]
for i in range(100):
ip='172.25.254.'+str(random.randint(1,255))
ips.append(ip)
pprint.pprint(ips)
一步搞定
print(['172.25.254.'+str(random.randint(1,255))
for i in range(100)])
显示 1~100之间的所有数求平方
print([i**2 for i in range(1,101)])
显示列表,1~100之间能被3整除数的平方
def is_div_three(num):
return num%3==0
print([i**2 for i in range(1,101) if is_div_three(i)])
import os 引用模块 相当于 ls
查找 换成大写
print([filename.upper() for filename in os.listdir('/var/log/') if filename.endswith('.log')])
def is_primme(num): 定义质数
if num<0: 小于0 不是
return False
elif num==1 and num==2:
return True
else:
for i in range(2,num): 可以被整除 不是
if num%i==0:
return False
else:
return True
for i in range(10): 查找 10 以内的质数
if is_primme(i):
print(i,end=',')
def is_primme(num):
if num<=0:
return False
elif num==1 and num==2:
return True
else:
for i in range(2,num):
if num%i==0:
return False
else:
return True
n=10
一步搞定
prims_list=[i for i in range(10) if is_primme(i)]
print(prims_list)
def is_primme(num):
if num<=0:
return False
elif num==1 and num==2:
return True
else:
for i in range(2,num):
if num%i==0:
return False
else:
return True
n=int(input('n:'))
prims_list=[i for i in range(n) if is_primme(i)]
count=0
for num1 in prims_list:
for num2 in prims_list:
if num1+num2==n and num1<=num2:
print(num1,num2)
count +=1
print(count)
上面是一个作业题
def is_primme(num):
if num<=0:
return False
elif num==1 and num==2:
return True
else:
for i in range(2,num):
if num%i==0:
return False
else:
return True
n=int(input('n:'))
prims_list=[i for i in range(n) if is_primme(i)]
count=0
for num1 in prims_list:
if n-num1 in prims_list and num1<=n-num1:
print(num1,n-num1)
count +=1
print(count) 另一种方法 比较简单
service={
'http':80,
'mysql':3306,
'ssh':22
}
将 k值变成大写
new_service={}
for key,value in service.items():
new_service[key.upper()]=value
print(new_service)
升级方法
print({k.upper():v for k,v in service.items()})
k值大写 value+1
print({k.upper():v+1 for k,v in service.items()})
大小写key值合并,统一以小写k值输出
d=dict(a=2,B=10,b=4,e=1,A=1)
print(d)
new_d={}
for k,v in d.items():
k=k.lower()
if k in new_d:
new_d[k] +=v
else:
new_d[k]=v
print(new_d)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python_lianxi.py
{'a': 2, 'B': 10, 'b': 4, 'e': 1, 'A': 1}
{'a': 3, 'b': 14, 'e': 1}
Process finished with exit code 0
print({k.lower():d[k.lower()]+d[k.upper()]
for k,v in d.items()}) 用字典生成式做 但是字母必须出现大写和小写
print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0)
for k,v in d.items()})
大小写可以不用同时存在, 后面的 0 代表 不存在时 报 0
集和生成式
print({i for i in range(10) if i%3==0})
d=dict(a=6,b=2)
print({k for k,v in d.items() if v%3==0})
print({v for k,v in d.items() if v%3==0})
运用到字典 一样
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python_lianxi.py
{'a': 2, 'B': 10, 'b': 4, 'e': 1, 'A': 1}
{'a'}
{6}
Process finished with exit code 0
print((i for i in range(100) if i%3==0))
生成器
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python_lianxi.py
{'a': 2, 'B': 10, 'b': 4, 'e': 1, 'A': 1}
<generator object <genexpr> at 0x7f58e64bb0f8>
Process finished with exit code 0
>>> g=(i for i in range(100) if i%3==0)
>>> type(g)
<class 'generator'> 生成器
>>> from collections import Iterable
>>> isinstance(g,Iterable) 可迭代
True
>>> g=(i for i in range(100) if i%3==0)
>>> g.__next__()
0
>>> g.__next__()
3
>>> g.__next__()
6 迭代原理
li=[i for i in range(100) if i%3==0] 生成式
li=(i for i in range(100) if i%3==0) 生成器
g1=(i for i in range(3)) 生成器
for 循环底层原理
while True:
try:
print(g1.__next__()) 进行下一把
except StopIteration: 遇到这个就结束
print('shengchengqijishu')
break
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python_lianxi.py
0
1
2
shengchengqijishu
Process finished with exit code 0
def fib(num): 菲薄纳妾 数列
a,b,count=0,1,1
while count<=num:
print(b,end=',')
a,b=b,a+b 赋值
count +=1
fib(5)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python_lianxi.py
1,1,2,3,5,
Process finished with exit code 0
def fib(num):
a,b,count=0,1,1
while count<=num:
yield b
a,b=b,a+b
count +=1
g=fib(5)
print(g.__next__())
print(g.__next__())
def chat_robot():
while True:
received=yield
g=chat_robot() 执行函数
g.__next__() 下一部 和yield 一块用
g.send('ls') 发送
简易机器人
def chat_robot():
res=''
while True:
received=yield res
if 'hello' in received or 'nianling' in received:
res='hello'
elif 'name' in received or 'xingming' in received:
res='wo shi xiao bing.....'
elif 'money' in received or 'qian' in received:
res='mei qian....'
else:
res='wo bu zhi dao ni zai shuo shen me'
def main():
Robot=chat_robot()
Robot.__next__()
while True:
send_data=input('chao>>:')
if send_data=='q' or send_data=='quit':
print('xiu xi......')
break
robot_data=Robot.send(send_data)
print('jia wei>>:',robot_data)
main()
def mypower(num):
return num**2
map(mypower,[1,2,3])
m=map(mypower,[1,2,3])
print(type(m),isinstance(m,Iterable))
for i in m:
print(i,end=',')
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
<class 'map'> True map 函数
1,4,9,
Process finished with exit code 0
def fun(num1,num2):
return num1+num2
m=map(fun,[1,2,3],{5,6,7}) 里面可以传函数
for i in m:
print(i)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
6
8
10
Process finished with exit code 0
def fun(*num):
return sum(num)
m=map(fun,[1,2,3],{5,6,7})
for i in m:
print(i)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
6
8
10
Process finished with exit code 0
from functools import reduce 引用模块
def add(x,y):
return x+y
print(reduce(add,range(5))) 累加 0 和 1 给 x y 然后 把0+1的值给 x 2 给y 一直这样到4
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
10
Process finished with exit code 0
from functools import reduce
def add(x,y):
return x*y 阶乘 1到4
print(reduce(add,range(1,5)))
from functools import reduce
def mypower(x,y):
return x*y
n=int(input('n:'))
l=reduce(mypower,range(1,n+1)) 阶乘
print(l)
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
n:5
120
Process finished with exit code 0
def is_odd(num):
return num%2==0
print(list(filter(is_odd,[12,34,56,1])))
print([i for i in [12,34,5] if i%2==0])
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
[12, 34, 56]
[12, 34]
Process finished with exit code 0
def is_prime(num): 判断 是否为质数
if num <=0:
return False
elif num==1 and num==2:
return True
else:
for i in range(2,num):
if num%i==0:
return False
else:
return True
def is_not_prime(num): 反向 判断是否 不为质数
return not is_prime(num)
print(is_not_prime(5)) 5 为质数 输出false
print(list(filter(is_not_prime,range(1,101)))) 符合的留下 不符合的删除
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
False
[4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49, 50, 51, 52, 54, 55, 56, 57, 58, 60, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 75, 76, 77, 78, 80, 81, 82, 84, 85, 86, 87, 88, 90, 91, 92, 93, 94, 95, 96, 98, 99, 100]
Process finished with exit code 0
info=[
['001','apple',100,2],
['002','xiaomi',10,2000],
['003','oppo',200,1900],
['004','computer',900,5000]
]
def sorted_by_count(item):
return item[2]
print(sorted(info,key=sorted_by_count))
/usr/local/bin/bin/python3.6 /root/PycharmProjects/untitled/day01/python__1.py
[['002', 'xiaomi', 10, 2000], ['001', 'apple', 100, 2], ['003', 'oppo', 200, 1900], ['004', 'computer', 900, 5000]]
Process finished with exit code 0 不懂