一、迭代
1、字典的迭代
1、key值迭代
d = dict(a=1,b=2)
for i in d:
print(i)
2、key->value值迭代
for i in d:
print("%s -> %s" %(i,d[i]))
3、key ->value迭代
for key,value in d.items():
print('%s -> %s' %(key,value))
2、判断对象是否可迭代
需要导入Iterable模块
from collections import Iterable ##导入模块
print(isinstance(1,int)) ##判断1是否是整形
print(isinstance(1,Iterable)) ##判断整形是否可迭代
print(isinstance(1.02,Iterable)) ##判断浮点型是否可迭代
print(isinstance(2e-9,Iterable)) ##判断浮点型是否可迭代
print(isinstance(True,Iterable)) ##判断bool型是否可迭代
print(isinstance('hello',Iterable)) ##判断字符串是否可迭代
print(isinstance({1,2,3,4},Iterable))#判断字典是否可迭代
2、字符串的迭代
for index,value in enumerate('hello'): ##enumerate 索引,讲hello字符串的索引值和元素对应打印
print(index,value)
二、列表生成式
1、随即生成100个ip
1、传统方式生成:
import random
ips = []
for i in range(100):
ip = '172.25.254.'+ str(random.randint(1,255))
ips.append(ip)
print(ips)
print(len(ips))
2.列表生成式:
import random
li = [ '172.25.254.'+str(random.randint(1,255)) for i in range(100)]
print(li)
print(len(li))
2、显示列表,1-100只见能被3整除的数的平方
def is_div_therr(num):
return num%3 ==0
print([num**2 for num in range(1,101) if is_div_therr(num)])
练习:
1、显示列表,1-1–只见的所有数求平方
print([i**2 for i in range(1,1011)])
2、找出/var/log/目录中所有以.log结尾的文件
import os
print([ filename for filename in os.listdir('/var/log') if filename.endswith('.log')])
3、找出/etc/目录中的所有以.conf结尾的文件,并把文件名转化为大写的文件名
print([ filename.upper() for filename in os.listdir('/etc/') if filename.endswith('.conf')])
4、判断10以内的所有质数,并找出质数相加等于10的质数对
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
n = 10
primes_list = [ num for num in range(10) if is_prime(num)]
primes_pair = [(num1,n-num1) for num1 in primes_list if n - num1 in primes_list and num1<= n-num1]
print(len(primes_pair))
print(primes_pair)
3、集合生成式
print({ i for i in range(10) if i % 3 ==0})
d = dict(a=6,b=2,c=3,e=6)
print({i for k,i in d.items() if i%3 ==0})
4、字典生成式
service = {'http':80,
'mysql':3306,
'ssh':22
}
需求1、将字典里面的key值变大写
##传统方法:
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()})
需求2、key值变成大写, value值在原有基础上加1
print({k.upper():v+1 for k,v in service.items()})
大小写合并,统一以小写key值输出
d = dict(a=2,b=10,B=4,e=1,A=1)
print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0) for k,v in d.items()}
5、生成器
1、列表生生成式转化为生成器
li = [ i for i in range(100) if i%2 ==0]
##生成器
g = (i for i in range(100) if i%2 ==0)
2、查看生成器的方式:
python3中 g.next方法(), python2.x中g.next()方法;
print(g.__next__())
3、生成器的for循环
for i in g:
print(i)
4、for循环 的底层原理
g1 = (i for i in range(3))
while True:
try:
print(g1.__next__())
except StopIteration:
break
5、fib生成器
fib是值后一个值是前两个值相加:1,1,2,3,5,8…
def fib(num): # num=5
a, b, count = 0, 1, 1 # a=0, b=1
while count <= num:
yield b # 1
a, b = b, a + b # a=1, b=1
count += 1
g = fib(10) # 如果函数中有yield关键字, 返回一个生成器对象;目前不执行函数内容;
print(g.__next__()) # 当遇到g.__next__方法时, 执行函数, 当遇到yield停止执行; print(g.__next__())时yield后面的值;
print(g.__next__()) # 再次调用g.__next__方法时, 从上次停止的地方继续执行, 遇到yield停止;
g.close() # 关闭生成器
#全部打印
for i in g:
print(i)
6、迷你机器人
def chat_robot():
res = ''
while True:
received = yield res
if 'age' in received or '年龄' in received:
res = '年龄保密'
elif 'name' in received or '姓名' in received:
res = '我是小冰'
elif 'money' in received or '钱' in received:
res = '没钱'
else:
res = '我不知道你在说什么,请换种方法'
def main():
Robot = chat_robot()
Robot.__next__()
while True:
send_data = input("my>>")
if send_data=='q' or send_data == 'quit':
print('我也要休息了')
break
robot_data = Robot.send(send_data)
print('小冰>>',robot_data)
main()