python基础



# 面试题
# for i in range(0, 10, -1):
# print(i)

# li = [1, 2, 5, 'a', [5, 6, 'kd'], "abc"]
# for i in li:
# if type(i) == list:
# for n in i:
# print(n)
# else: print(i)

# key1 = []
# key2 = []
# dic = {}
# li = [11, 23, 33, 44, 55, 66, 77, 88, 99]
# for i in li:
# if i > 66:
# key1.append(i)
# else:
# key2.append(i)
# dic.setdefault("k1", key1)
# dic.setdefault("k2", key2)
# print(dic)

# while 1:
# li = ["手机", "电脑", "鼠标", "游艇"]
# for i in li:
# print(li.index(i)+1, i)
# chioce = input("请输入数字,Q 或者q退出>>>")
# if chioce.isdigit():
# chioce = int(chioce)
# if chioce > 0 and chioce <= len(li):print(li[chioce-1])
# else:print("请输入有效数字")
# elif chioce.upper() == "Q":break
# else:print("请输入数字")

# a = 300
# b = 300
# print(id(a), id(b))
# i = "alex@"
# c = "alex@"
# print(i is c)

# s1 = '中文'
# # encode 编码, 如何将str -->bytes
# s11 = s1.encode('utf-8')
# print(s11)
# s22 = s1.encode('gbk')
# print(s22)

# f = open('C:/Users/陶政全/Desktop/个人/python面试笔记.txt', 'r', encoding="utf-8").read()
# print(f)

# # 修改文件
# with open('file', encoding='utf-8') as f, open('files', 'w', encoding='utf-8') as f2:
# for line in f:
# if 'nice' in line:
# line = line.replace("nice", "good")
# f2.write(line)
#
# import os
# os.remove("file") # 删除文件
# os.rename("files", "file") # 改文件名

s = '42425252'
b = '1425'
# n = 0
# print(len(s))
# for i in s:
# n += 1
# print(n)


# def func(s):
# i = 0
# for k in s:
# i += 1
# return i
# lenght = func(b)
# print(lenght)

# li = [1, 3, 2, 'a', 4, 'b', 5, 'c']
# l3 = li[::2]
# print(l3)
# l4 = li[1:6:2]
# print(l4)
# l5 = li[-1:]
# print(l5)
# l6 = li[-3::-2]
# print(l6)

# lis = [['k', ['qwe', 20, {'k1': ['tt', 3, '1']}, 89], 'ab']]
# lis[0][1][2]['k1'][0] = "TT"
# print(lis)
# print(lis[0][1][2]['k1'][0].upper())
# lis[0][1][2]['k1'][1] = "100"
# lis[0][1][2]['k1'][1] = str(lis[0][1][2]['k1'][1]+97)
# lis[0][1][2]['k1'][2] = 101
# lis[0][1][2]['k1'][2] = int(lis[0][1][2]['k1'][2])+100
# print(lis)

# dic = {'k1': "v1", 'k2': ['alex', 'sb'], (1, 2, 3, 4, 5): {'k3': ['2', 100, 'wer']}}
# dic['k2'].append('23')
# dic['k2'].insert(0, 'a')
# print(dic)
# dic[(1, 2, 3, 4, 5)].setdefault('k4','v4')
# dic[(1, 2, 3, 4, 5)].setdefault((1,2,3),'ok')
# dic[(1, 2, 3, 4, 5)]['k3'][2] = 'qq'
# print(dic)

# int加引号就是str ;int, str 必须是数字才能转化
# int 转化成bool, 0为FALSE 其他为TRUE
# str 转化成bool,空为FALSE 其他为TRUE
# str.split()转化为list

# li = ['alex', 'wusir', 'rain']
# lis = ''.join(li)
# print(lis)
# lis = '*'.join(li)
# print(lis)
# li = 'alexwusirlex'
# lis = li[0].split(',') + li[1:].split(',')
# print(lis)
# li = 'alex wusir'
# lis = li.replace(' ', ',').split(',')
# print(lis)
# li = 'alex'
# lis = '_'.join(li)
# print(lis)

# sum = 0
# for i in range(1, 100):
# if i%2 == 0:
# sum -= i
# else:
# sum += i
# print(sum)
# n = 1
# # sum = 0
# # while n<100:
# # if n%2 == 0:
# # sum -= n
# # else:
# # sum +=n
# # n +=1
# # print(sum)

# for i in range(100,-1,-1):
# print(i)

# count = 0
# s = input(">>>")
# for i in range(len(s)):
# if i % 2 == 1 and s[i].isdigit():
# count += 1
# print(count)

# l1 = []
# l2 = []
# dic ={}
# li = [11, 22, 33, 44, 55, 66, 77, 88, 99]
# for i in li:
# if i > 66:
# l2.append(i)
# else:
# l1.append(i)
# dic.setdefault("key1", l1)
# dic.setdefault("key2", l2)
# print(dic)

# li = ['taibai', 'alexC', 'Abc', 'egon', 'Ritian', 'Wusir', 'aqc']
# lis = []
# for i in li:
# i.replace(' ', '')
# if i.startswith("A") or i.startswith('a') or i.endswith('c'):
# lis.append(i)
# print(lis)


# from urllib.request import urlopen
# def get_url():
# url = 'http://www.xiaohua100.cn/index.html'
# def get():
# ret = urlopen(url).read()
# print(ret)
# return get
# get_func = get_url()
# get_func()

# def all_sum(*args):
# sum1 = sum(args)
# return sum1
# print(all_sum(1, 2, 6))


# def all_sum(args):
# if len(args) > 2:
# a = args[:2]
# return a
# print(all_sum('asdfgh'))

# def func(s):
# num = 0
# alpha = 0
# space = 0
# other = 0
# for i in s:
# if i.isdigit():
# num += 1
# elif i.isalpha():
# alpha += 1
# elif i.isspace():
# space += 1
# else:
# other += 1
# return num, alpha, space, other
# print(func("dfaf161ga6 16afa 16"))

# def func(filename, old, new):
# with open(filename, encoding='utf-8') as f, open('%s.txt'%filename, 'w', encoding='utf-8') as f1:
# for line in f:
# if old in line:
# line = line.replace(old, new)
# f1.write(line)
# import os
# os.remove(filename)
# os.rename('%s.txt'%filename, filename)
# func()


# from functools import wraps
# def wrapper(func): # 1 装饰函数
# @wraps(func)
# def inner(*args, **kwargs): # 4
# print("大家好") # 5
# ret = func(*args, **kwargs) # 6
# # print("++++")
# return ret # 9
# # print("***", inner, func)
# return inner #
#
# @wrapper # 语法糖 # 3
# def index(*args, **kwargs): # 2
# print("你好", args) # 7
# return args # 8
# # index = wrapper(index) === @wrapper
# print(index.__name__)
# ttt = index(1, 2, 3, 4) # inner() 10
# print(ttt) # 11


# a = (1, 2, 3)
# a1 = a[:]
# print(id(a) == id(a1))

# ======生成器=======
# def scq():
# for i in range(50):
# print('===')
# yield i
# ret = scq()
# print(ret)
# ret1 = ret.__next__()
# print(ret1)
# ret1 = ret.__next__()
# print(ret1)
# ret1 = ret.__next__()
# print(ret1)

# ===生成器2====

# def generator():
# print(123)
# contect = yield 1
# print('----', contect)
# print(456)
# yield 2
# g = generator()
# ret = g.__next__()
# print('***', ret)
# ret = g.send('hello') # send的效果和next一样
# print('***', ret)
# # send获取下一个值的时候, 给上一个yield的位置传递一个数据
# # 使用send的注意事项
# # 第一次使用生成器的时候 是用next获取下一个值
# # 最后一个yield不能接受外部的值

# ===== 装饰器和生成器的使用====

# def init(func):
# def inner(*args, **kwargs):
# g = func(*args, **kwargs)
# g.__next__()
# return g
# return inner
# @init
# def average():
# sum = 0
# count = 0
# avg = 0
# while True:
# num = yield avg
# sum += num
# count += 1
# avg = sum/count
# avg_g = average()
# ret = avg_g.send(10)
# print(ret)
# ret = avg_g.send(20)
# print(ret)


# def generator():
# a = 'abcde'
# b = '12345'
# for i in a:
# yield i
# for i in b:
# yield i
# ======上面跟下面的效果一样=======
# def generator():
# a = 'abcde'
# b = '12345'
# yield from a
# yield from b
# g = generator()
# for i in g:
# print(i)

# 装饰器
# def tail(filename):
# f = open(filename, encoding='utf-8')
# while True:
# line = f.readline()
# if line:
# yield line.strip()
#
# g = tail('file')
# for i in g:
# if 'python' in i:
# print(i)


# def wahaha():
# """
# 查看注释的语句
# :return:
# """
# print("哈哈哈")
# print(wahaha.__name__) # 查看字符串的格式函数名
# print(wahaha.__doc__) # document

# # 1.编写装饰器, 为多个函数加上认证的功能(用户的账号密码来源于文件),
# # 要求登录成功,后续的函数都无需再输入用户名和密码
# from functools import wraps
# FLAG = False
# def login(func):
# @wraps(func)
# def inner(*args, **kwargs):
# global FLAG
# if FLAG:
# ret = func(*args, **kwargs)
# return ret
# else:
# username = input('username>>>')
# password = input('password>>>')
# if username == '123' and password == '123':
# FLAG = True
# ret = func(*args, **kwargs)
# return ret
# else:
# print("登入失败")
# return inner
# @login
# def shoplist_add():
# print("增加一件物品")
# @login
# def shoplist_del():
# print("删除一件物品")
# shoplist_add()
# shoplist_del()

# # 登入日志
# from functools import wraps
# import time
# def log(func):
# @wraps(func)
# def inner(*args, **kwargs):
# with open('file', 'a', encoding='utf-8') as f:
# f.write(func.__name__+'\n'+time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())+'\n')
# ret = func(*args, **kwargs)
# return ret
# return inner
#
# @log
# def shoplist_add():
# print('增加')
# @log
# def shoplist_del():
# print('减少')
# shoplist_del()
# shoplist_add()


# # 创建一个装饰器 检验本地是否有东西 没有从网上下载下来
# from urllib.request import urlopen
# import os
# from functools import wraps
#
# def cache(func):
# @wraps(func)
# def inner(*args, **kwargs):
# if os.path.getsize('file'):
# with open('file', 'r', encoding='utf-8') as f:
# return f.read()
# ret = func(*args, **kwargs)
# with open('file', 'wb') as f:
# f.write(ret)
# return ret
#
# return inner
# @cache
# def get(url):
# code = urlopen(url).read
# return code
# ret = get('http://www.baidu.com')
# print(ret)


# # 带参数的装饰器
# import time
# FLAGE = True
# def timmer_out(flag):
# def timmer(func):
# def inner(*args, **kwargs):
# if flag:
# start = time.time()
# ret = func(*args, **kwargs)
# end = time.time()
# print(end - start)
# return ret
# else:
# ret = func(*args, **kwargs)
# return ret
# return inner
# return timmer
# timmer = timmer_out(FLAGE)
# @timmer
# def wahaha():
# time.sleep(0.1)
# print("hahahha")
# @timmer
# def ennene():
# time.sleep(0.1)
# print("enenen")
# wahaha()
# ennene()

# name = [['Tom', 'errss', 'Ling'],
# ['Fass', 'eles', 'dkcl']]
# ret = [i for lit in name for i in lit if i.count('s') == 2]
# print(ret)

# 1.生成器重点数据只能取一次, 取完就没有 2.惰性运算,不找到取值,他就不工作
# def demo():
# for i in range(4):
# yield i
# g=demo()
# g1=(i for i in g)
# g2=(i for i in g1)
# print(list(g1))
# print(list(g2))

# # ======面试题=====
# def add(n,i):
# return n+i
# def test():
# for i in range(4):
# yield i
# g=test()
# for n in [1,10]:
# g=(add(n,i) for i in g)
# # n=1
# # g = (add(n,i) for i in g)
# # n =10
# # g = (add(10, i) for i in (add(10,i) for i in (test())))
# print(list(g))

# def file(s):
# with open(s, 'r', encoding='utf-8') as f:
# name = input('>>>')
# for line in f:
# if name in line:
# yield '***'+line
# g = file('file')
# for i in g:
# print(i.strip())
# ====面试题===
# def test():
# for i in range(4):
# yield i
# g = test()
# for i in [10, 2]:
# g = (i+n for n in g)
#
# # i = 10
# # g = (i+n for n in test())
# # i = 2
# # g = (i+n for n in (i+n for n in test())
# print(list(g))



# print(divmod(9, 5))
# print(abs(-5))
# print(round(3.1415, 2))
# print(pow(2, 3))
# print(3>2==2)

# ============重要知识点==========
# def is_str(s):
# return type(s) == str
# ret = filter(is_str, [1, 'hello', 6, 7, 'world', 12, 17])
# print(ret)
# for i in ret:
# print(i)


# from math import sqrt
# def func(num):
# ret = sqrt(num)
# return ret % 1 == 0
# ret = filter(func, range(1, 101))
# for i in ret:
# print(i)

# ret = map(abs, [1, -4, 6, -8])
# print(ret)
# for i in ret:
# print(i)

# filter 执行了filter之后的结果集合<=执行之前的个数
# filter只管筛选,不会改变原来的值
# map执行前后元素个数不变
# 值可能发生改变


# l = [1, -4, 6, 5, -10]
# # l.sort(key = abs) # 在原来列表的基础上进行排序
# # print(l)
#
# print(sorted(l, key=abs, reverse=True)) # 生成了一个新列表 不改变原来列表
# print(l)

# 列表中元素按长度排序
# l = [' ', [1, 2], 'hello world', 'nihao']
# new_l = sorted(l, key=len)
# print(new_l)

# dic = {'k1': 10, 'k2': 100, 'k3': 30}
# print(max(dic, key=lambda k: dic[k]))

# 现在有两个元祖(('a'),('b')),(('c'),('d'))
# 请使用python中匿名函数生成列表[{'a', 'b'},{'c','d']

# zip
# ret = zip((('a'), ('b')), (('c'), ('d')))
# for i in ret:
# print(i)

# ret = zip((('a'), ('b')), (('c'), ('d')))
# res = map(lambda tup: {tup[0]: tup[1]}, ret)
# print(list(res))

# def multipliers():
# return [lambda x: i*x for i in range(4)]
# print([m(2) for m in multipliers()])

# name = ['alex', 'wupeiqu', 'yuanhao', 'nezha']
# ret = map(lambda item: item+'_sb', name)
# print(list(ret))

# 用filter函数处理数字列表, 将列表中所有的偶数筛选出来
# num = [1, 3, 5, 6, 7, 8]
# def func(x):
# return x % 2 == 0
# ret = filter(func, num) # ret是迭代器
# print(list(ret))
# ret = filter(lambda x:x%2==0, num)
# print(list(ret))


# ===============分页方法===============
# with open('file', encoding='utf-8') as f:
# l = f.readlines()
# page_num = int(input(">>>"))
# pages, mod = divmod(len(l), 5)
# if mod:
# pages += 1
# if page_num > pages or page_num <= 0:
# print('输入有误')
# elif page_num == pages and mod != 0:
# for i in range(mod):
# print(l[(page_num-1)*5+i].strip())
# else:
# for i in range(5):
# print(l[(page_num-1)*5 +i].strip())


protfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'PPM', 'shares': 50, 'price': 543.22},
{'name': 'HPO', 'shares': 200, 'price': 32.1}
]
# 计算购买每只股票的总价
ret = map(lambda dic: {dic['name']: dic['shares']*dic['price']}, protfolio)
print(list(ret))
# 用filter过滤出,单价大于100的股票有哪些
res = filter(lambda dic: dic['price'] > 100, protfolio)
print(list(res))

转载于:https://www.cnblogs.com/taozhengquan/p/9463377.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值