怎么⽤for循环实现把字符串变成Unicode码位的列表
>>> str = '!@#$%^&*('
>>> codes = []
>>> for i in str:
... codes.append(ord(i))
...
>>> codes
[33, 64, 35, 36, 37, 94, 38, 42, 40]
怎么⽤列表推导式实现把字符串变成Unicode码位的列表
>>> codes = [ord(i) for i in str]
>>> codes
[33, 64, 35, 36, 37, 94, 38, 42, 40]
打印出两个列表的笛卡尔积
# 使⽤⽣成器表达式产⽣笛卡尔积,可以帮忙省掉运⾏ for 循环的开销。
>>> colors = ['blacks','white']
>>> sizes = ['s','m','l']
>>> for tshirt in ('%s %s'%(i,j) for i in colors for j in sizes):
... print(tshirt)
...
blacks s
blacks m
blacks l
white s
white m
white l
# 使⽤ itertools ⾥的 product ⽣成器函数
>>> c = list(itertools.product(colors,sizes))
>>> c
[('blacks', 's'), ('blacks', 'm'), ('blacks', 'l'), ('white', 's'), ('white', 'm'), ('white', 'l')]
# 可迭代对象拆包时,怎么赋值给占位符
>>> for i, _ in c:
... print(i)
...
blacks
blacks
blacks
white
white
white
⽤什么⽅式接收不确定值或参数
# ⽤ *args 的⽅式,*args 位置可以在任意位置
>>> a,b,*c = range(8)
>>> a,b,c
(0, 1, [2, 3, 4, 5, 6, 7])
# ⽤切⽚将对象倒序
>>> s = 'basketball'
>>> s[::-1]
'llabteksab'
# 怎么查看列表的 ID
>>> id(c)
140681867559368
# 怎么通过 reverse 参数对序列进⾏降序排列,
# 默认值为 False,默认升序排列,降序排列的话需要将 reverse 值设置为 True。
>>> l
[1, 9, 5, 8]
>>> sorted(l,reverse=True)
[9, 8, 5, 1]
# numpy 怎么把⼀维数组变成⼆维数组
import numpy
a = numpy.arange(12)
print(a)
a.shape = 3, 4
print(a)
[ 0 1 2 3 4 5 6 7 8 9 10 11]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
# 快速插⼊元素到列表头部
# 可以通过切⽚指定位置插⼊
>>> l = [1, 2, 3, 4]
>>> l[0:0] = 'ab'
>>> l
['a', 'b', 1, 2, 3, 4]
>>> l[0] = 'ab'
>>> l
['ab', 'b', 1, 2, 3, 4]
# 可以通过 insert() ⽅法插⼊,第⼀个参数是位置的坐标,从 0 开始
>>> l.insert(1, 'py')
>>> l
['ab', 'py', 'b', 1, 2, 3, 4]
# 在第⼀个元素之前添加⼀个元素之类的操作是很耗时的,因为这些操作会牵扯到移
# 动列表⾥的所有元素。⾼效的⽅法,⽤双向队列 deque 类。
# deque 类可以指定这个队列的⼤⼩,如果这个队列满员了,还可以从反向端删除过期的元素,然后在尾端# # 添加新的元素
>>> from collections import deque
>>> dp = deque(range(10),maxlen=9)
>>> dp
deque([1, 2, 3, 4, 5, 6, 7, 8, 9], maxlen=9)
>>> dp.appendleft(-1)
>>> dp
deque([-1, 1, 2, 3, 4, 5, 6, 7, 8], maxlen=9)
怎么统计字符串中元素出现的个数
# 怎么统计字符串中元素出现的个数
>>> import collections
>>> ct = collections.Counter('adcfadcfgbsdcv')
>>> ct
Counter({'d': 3, 'c': 3, 'a': 2, 'f': 2, 'g': 1, 'b': 1, 's': 1, 'v': 1})
# 怎么统计出排名前n的元素
>>> ct.most_common(3)
[('d', 3), ('c', 3), ('a', 2)]
# 求m中元素在n中出现的次数
>>> m
{'c', 'b', 'a'}
>>> n
{'c', 'd', 'b'}
>>> for j in m:
... if j in n:
... i += 1
...
>>> i
2
>>> len(m & n)
2
>>> len(set(m) & set(n))
2
⽤递归实现阶乘
# ⽤递归实现阶乘
>>> def fact(n):
... """:return n!"""
... return 1 if n<2 else n* fact(n-1)
...
>>> all([])
True
>>> any([])
False
>>> fact(5)
120
# 不使⽤递归,怎么⾼效写出阶乘表达式
>>> from functools import reduce
>>> from operator import mul
>>> def fact(n):
... return reduce(mul,range(1,n+1))
...
>>> fact(5)
120
# 测试代码运⾏的时间
import time
# t = time.perf_counter()
# for i in range(10000):
# pass
# t1 = time.perf_counter()
# print(t1-t)
t0 = time.time()
for i in range(10000):
pass
t1 = time.time()
print(t1 - t0)
使⽤装饰器 functools.lru_cache() 缓存数据
import functools
@functools.lru_cache()
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-2) + fibonacci(n-1)
print(fibonacci(8))
⽐较两个对象的内存地址 id 是否相等
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a is b
False
# 怎么格式化显示对象
>>> from datetime import datetime
>>> now = datetime.now()
>>> format(now,'%H:%M:%S')
'17:46:48'
>>> "It's now {:%I:%M%p}".format(now)
"It's now 05:46PM"
# 复制⼀个序列并去掉后 n 个元素
>>> l = [1,2,3,4,5]
>>> j = l[:-2]
>>> j
[1, 2, 3]
# Python中怎么定义私有属性。
# 在属性前加两个前导下划线,尾部没有或最多有⼀个下划线
# 怎么随机打乱⼀个列表⾥元素的顺序
>>> from random import shuffle
>>> l = list(range(30))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
>>> shuffle(l)
>>> l
[23, 24, 19, 4, 17, 18, 0, 25, 8, 13, 12, 10, 6, 22, 20, 26, 3, 7, 27, 28, 16, 21, 14, 2, 29, 1, 11, 9, 5, 15]
# 怎么判断某个对象是⼀个已知的类型
>>> isinstance("a",int)
False
>>> isinstance(10,int)
True
>>> isinstance("a",str)
True
# 怎么打印出分数
>>> from fractions import Fraction
>>> print(Fraction(1,3))
1/3
关于+=的⼀道谜题
# + 和 += 区别
# 两边必须是同类型的对象才能相加,+= 右操作数往往可以是任何可迭代对象。
>>> t = (1, 2, [30, 40])
>>> t[2] += [50, 60]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [30, 40, 50, 60])
# 怎么列出⼀个⽬录下所有的⽂件名和⼦⽂件名
>>> import os
>>> dirs = os.walk('/root')
>>> for dir in dirs:
... print(dir)
...
('/root', ['PbootCMS', '.config', '.cache', '.ipython', '.pip', '.pki', '.ssh'], ['mysql57-community-release-el7-10.noarch.rpm', '.bash_history', 'a.txt', '.viminfo', '.bash_logout', '.bash_profile', '.cshrc', '.lesshst', '.pydistutils.cfg', '.tcshrc', '.bashrc', '.mysql_history', '.python_history'])
# 怎么返回 1 到 10 的阶乘列表
>>> import itertools
>>> import operator
>>> list(itertools.accumulate(range(1,11),operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
# 怎么快速拼接字符串和序列形成新的列表
>>> import itertools
>>> list(itertools.chain('ABC',range(5)))
['A', 'B', 'C', 0, 1, 2, 3, 4]
# 进度条显示
import time
from tqdm import tqdm
for i in tqdm(range(100)):
time.sleep(.01)
100%|██████████| 100/100 [00:01<00:00, 63.98it/s]
sort() 和 sorted() 区别
>>> l = [1, 9, 12, 8]
>>> k = sorted(l)
>>> k
[1, 8, 9, 12]
>>> print(l.sort())
None
# sort() 会在原序列上排序,这也是这个⽅法的返回值是None的原因,提醒你本⽅法不会新建⼀个列表
# 其实是Python的⼀个惯例:如果⼀个函数或者⽅法对对象进⾏的是就地改动,那它
# 就应该返回None,好让调⽤者知道传⼊的参数发⽣了变动,⽽且并未产⽣新的对象。
# sorted() 新建了⼀个新的序列。
可变序列⽤*=后,会创建新的序列吗
# 不会,可变序列⽤*=后,不会创建新的序列
>>> l = [1, 2, 3, 4]
>>> id(l)
140334772576584
>>> l *= 2
>>> l
[1, 2, 3, 4, 1, 2, 3, 4]
>>> id(l)
140334772576584
# 可变序列⽤*=后,会创建新的序列吗
>>> l = 'abc'
>>> id(l)
140334773568656
>>> l *= 2
>>> l
'abcabc'
>>> id(2)
140334772082624
字典的创建⽅法
>>> a = dict(name='jack', age=20, hobby='play')
>>> a
{'name': 'jack', 'age': 20, 'hobby': 'play'}
>>> b = {'name':'jack', 'age':20, 'hobby':'play'}
>>> b
{'name': 'jack', 'age': 20, 'hobby': 'play'}
>>> c = dict(zip(['name', 'age', 'hobby'],['jack', 20, 'paly']))
>>> c
{'name': 'jack', 'age': 20, 'hobby': 'paly'}
>>> d = dict([('age', 20),('name','jack'),('hobby','play')])
>>> d
{'age': 20, 'name': 'jack', 'hobby': 'play'}
>>> e = dict({'one': 1, 'two': 2, 'three': 3})
>>> e
{'one': 1, 'two': 2, 'three': 3}
# ⽤字典推导(dictcomp)构建字典
>>> dial_code = [
... (86, 'China'),
... (91, 'India'),
... (1, 'US'),
... (55, 'Brazil'),
... (7, 'Russia'),
... (81, 'Japan')
... ]
>>> coutry_code = {coutry:code for code, coutry in dial_code}
>>> coutry_code
{'China': 86, 'India': 91, 'US': 1, 'Brazil': 55, 'Russia': 7, 'Japan': 81}
>>>
# ⽤setdefault⽅法,只查询⼀次,效果更快
>>> coutry_code.setdefault('china', []).append(86)
>>> coutry_code
{'China': 86, 'India': 91, 'US': 1, 'Brazil': 55, 'Russia': 7, 'Japan': 81, 'china': [86]}
# 如果⽤下⾯这种⽅法,需要查询三次
>>> if 'china' not in coutry_code:
... coutry_code['china'] = []
... coutry_code['china'].append(86)
...
>>> print(coutry_code)
{'China': 86, 'India': 91, 'US': 1, 'Brazil': 55, 'Russia': 7, 'Japan': 81, 'china': [86]}