列表生成式
import random
# li = []# for i in range(10):
# li.append(random.randint(1,10))
# # 普通的列表生成式;
# print([random.randint(1,10) for i in range(10)])
# print([i*i for i in range(1,8)])
# 升级版本
# 1. 找出1~10之间所有的偶数;
# print([i for i in range(1,11) if i%2==0])
# 2. 找出1~1000之间所有的质数;
# def isPrime(num):
# pass
# print([i for i in range(1,1001) if isPrime(i)])
# # 3.for嵌套for循环;
# # 'ABC', '123'
# print([i+j for i in 'ABC' for j in '123'])
列表生成式练习
# 找出/var/log/目录中,所有以.log结尾的文件名或者目录名;
# os.listdir('/var/log/')
# if
import osprint([filename for filename in os.listdir('/var/log') if filename.endswith('.log')])
# 2. 将列表中所有内容都变为小写;
li = ['frdgrfgdsHHJJ', 'cdsfregHHHJDGF']
print([i.lower() for i in li])
字典生成式
# d = dict(a=1,b=2)
# print("小写的字典:", d)
# 1. 需求1: 将所有的key值变为大写;
## 传统方法:
# new_d = {}
# for i in d: # 'a' 'b'
# new_d[i.upper()] = d[i]
# print("key转化为大写的字典:", new_d)
## 升级
# print({k.upper():v for k,v in d.items()})
# # 需求2:大小写key值合并, 统一以小写key值输出;
d = dict(a=2, b=1, c=2, B=9, A=5)
## 字典生成式:
print({k.lower():d.get(k.lower(),0)+d.get(k.upper(),0) for k in d})
# 传统方法:
# # {'a':2, 'b':1, 'c':2}
# new_d = {}
# for k, v in d.items():
# low_k = k.lower()
# if low_k not in new_d:
# new_d[low_k] = v
# else:
# new_d[low_k] += v
# print(new_d)
# new_d = {}
# for k,v in d.items():
# lower_k = k.lower()
# if lower_k in new_d:
# new_d[lower_k] += d[k]
# else:
# new_d[lower_k] = d[k]
# print(new_d)
# new_d = {k.lower():d.get(k.lower(),0)+d.get(k.upper(),0) for k in d}
# print(new_d)
# # # 需求3: 把字典的key和value值调换;
# d = {'a':'1', 'b':'2'}
# print({v:k for k,v in d.items()})
集合生成式
print({i ** 2 for i in {1, 2, 3}})
print({i ** 2 for i in {1, 2, 3, 9, 12} if i % 3 == 0})
生成器的第2中实现方式
# # 生成器
# # 1. 列表生成式修改为生成器
# li = [i for i in range(100) if i%2==0]
# # 生成器
# g = (i for i in range(100) if i%2==0)
# # 2. 查看生成器内容的两种方式
# ## 2-1.python3中 g.__next__方法(), python2.x中g.next();
# # python2.x, python3.x, next(g)
# # print(g.__next__())
# # print(g.__next__())
# # print(g.__next__())
# # print(next(g))
# ## 2-2. for循环
# # isinstance(1, int)
# # isinstance(1, (int, float))
# from collections import Iterable
# print(isinstance(g, Iterable))
# # for i in g:
# # print(i)
# while True:
# try:
# print(g.__next__())
# except StopIteration:
# # print('end')
# break
# __next__()
# send('xxxx')
# close()
# throw()
# g = (i**2 for i in range(5))
#
# print(g.__next__())
# # g.close()
# print(g.__next__())
def gen():
while True:
try:
yield 'a'
except TypeError:
print('type error')
# throw方法:给生成器发送一个异常(错误); 但是不影响g.__next__()的执行;
# close(): 关闭生成器, 再次执行g.__next__()报错;
g = gen()
print(g.__next__())
g.throw(TypeError)
print(g.__next__())
打印斐波那契数列列前十十列列,示例例如下(语言言不不限):
1 1 2 3 5 8 13 21 34 55 ....
def fib(num):
a, b, count = 0, 1, 1 # 0, 1
while count <= num:
print(b)
a, b = b, a + b #a=2, b=3
count += 1
fib(10)
fib数列生成器的实现
1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器;
def fib(num):
a, b, count = 0, 1, 1 # 0, 1
while count <= num:
yield b
a, b = b, a + b #a=2, b=3
count += 1
g = fib(10)
for i in g:
print(i)
yield理解
# 1. 当在函数中看到yield关键字, 那么这个函数调用的返回值是一个生成器;
# 2. 当要执行函数fun时, 必须调用g.__next__();
# 3. 函数执行时, 直到遇到yield停止;
# 4. 想要继续执行, 调用g.__next__();从上一次停止的地方继续执行;
def fun():
a = "world"
print("hello")
print(1)
yield 2
print(3)
yield 4
g = fun()
print(g)
for i in g: # g.__next__()
print(i)
生产者消费者模型
# def consumer(name):
# print("%s will buy tea..." %(name))
# while True:
# kind = yield
# print("%s already buy %s tea" %(name,kind))
# g = consumer("zhao")
# g.__next__()
# g.send("A")
import random
import time
def consumer(name):
print("%s will buy tea..." %(name))
while True:
kind = yield
print("%s already buy %s tea..." %(name,kind))
def producer(name):
p1 = consumer("wang")
p2 = consumer("li")
p1.__next__()
p2.__next__()
print("cooker %s will make tea..." %(name))
for kind in ['A','B','C']:
time.sleep(random.random())
print("%s make %s tea" %(name,kind))
p1.send(kind)
p2.send(kind)
producer('zhang')
协程理解
协程是一种允许在特定位置暂停或恢复的子程序——这一点和生成器相似。
但和生成器不同的是,协程可以控制子程序暂停之后代码的走向,而生
成器仅能被动地将控制权交还给调用者。
练习1:
假设有两个子程序main和printer。printer是一个死循环,等待输入、
加工并输出结果。main作为主程序,不时地向printer发送数据。
加工: [1] text
[2] text
这应该怎么实现呢?
def printer():
counter = 1
while True:
text = yield
print("[%d] %s" %(counter,text))
counter +=1
def main():
p = printer()
p.__next__()
for i in range(10):
p.send('8888')
main()
生成器_迷你聊天机器人
def char_robot():
res = ''
while True:
receive = yield
if 'name' in receive:
res = "cat"
elif 'hello' in receive:
res = "heloo"
elif 'age' in receive:
res = '18'
elif 'country' in receive:
res = 'China'
elif 'weather' in receive:
res = 'rain'
elif 'create' in receive:
res = 'computer'
else:
res = 'i dont know'
print("Robot>>:%s" %(res))
def main():
Robot = char_robot()
next(Robot)
while True:
send_data = input("A>>:")
if send_data == 'q' or send_data == 'bye':
print('byebye~')
break
robot_said = Robot.send(send_data)
main()
内置高阶函数_map_reduce
高阶函数: 实参可以是一个函数; 返回值可以是一个函数;
普通函数:
# 函数定义:
def 函数名(形参): def add(a, b):
函数体
return 返回值 return 1
# 调用函数;
函数名(实参) add(1,2)
print(函数名(实参) )
# print(abs(-5))
# a = abs
# print(a(-5))
# 内置高阶函数
# 1. map函数理解
from collections import Iterable
# def func(x):
# return x**2
# f = map(func, [0,1,2,3,4])
# # print(isinstance(f, Iterable))
# for i in f:
# print(i)
# 1. map函数练习
# 需求: 用户接收一串数字; '1 3 5 7 8', 将该字符串中的所有数字转化为整形,并以列表格式输出;
s = '1 3 5 7 8'
# a, b, c, d, e = list(map(int, s.split()))
# print(a,e)
print([int(i) for i in s.split()])
# reduce在python3.x不是内置高阶函数, 而是需要导入from functools import reduce;
# In [2]: def add(x,y):
# ...: return x+y
# ...:
# In [3]: reduce(add, [1,2,3,4,5,6])
# Out[3]: 21
# In [4]: (((1+2)+3)+4)
# from functools import reduce
# # def add(x,y):
# # return x+y
# # print(reduce(add, range(5)))
# # 需求: 用户输入数字n; 求n的阶乘; 5!= 1*2*3*4*5
# def func(x,y):
# return x*y
# print(reduce(func, range(1,6))) # func(func(1,2),3)
高阶函数_filter_sorted
# filter高阶函数: filter(func, iterable)
# 1. func: 只有一个形参, 函数的返回值只能是True或者False;
def isodd(num):
if num %2 == 0:
return True
else:
return False
print(list(filter(isodd, range(10))))
def isPrime(num):
pass
print(list(filter(isPrime, range(1000))))
# sorted:
# 排序: 由大到小
print(sorted([23,56546,78]))
# 排序: 由小到大, reverse=True, 代表排序后进行反转;
print(sorted([23,56546,78], reverse=True))
info = [
['001', 'apple', 1000, 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))
# 需要按照商品的价格进行排序, 最终显示价格最高的商品名称和商品数量;
def sorted_by_price(item):
return item[-1]
sorted_by_price_info = sorted(info, key=sorted_by_price)
print(sorted_by_price_info[-1][1], sorted_by_price_info[-1][2])
info = {
'001':{
'name':'apple',
'count':1000,
'price':2
},
'002': {
'name': 'xiaomi',
'count': 10,
'price': 2000
},
'003': {
'name': 'Oppo',
'count': 200,
'price': 1900
}
}
def dict_sorted_by_count(item):
return item['count']
print(sorted(info.values(), key=dict_sorted_by_count))
sorted函数应用_携程笔试_移动数组中的0
(2018-携程-春招题)题目需求:
给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
# 输入:
第一行是数组长度, 后续每一行是数组的一条记录;
4
0
7
0
2
# 输出:
调整后数组的内容;
7
2
0
0
"""
n = int(input("数组长度:"))
li = [int(input()) for i in range(n)]
for i in sorted(li, key=lambda x: 1 if x is 0 else 0): print(i)
# def move_zero(item):
# if item == 0:
# return 1
# else:
# return 0
# for i in sorted(li, key=move_zero):
# print(i)