python必考题答案,python常见考题

大家好,小编为大家解答python必考题答案的问题。很多人还不知道python常见考题,现在让我们一起来看看吧!

一、信息过滤
1.1 警告

忽略警告

import warnings
warnings.filterwarnings('ignore')
二、相关知识点
2.1 if else 写一行
num = 1 if param > 10 else 0 
2.2 求交集,差集,并集
 list(set(a).intersection(set(b)))

求交集

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

set1 = set(list1)
set2 = set(list2)

intersection = set1 & set2

print(intersection)  # 输出 {4, 5}

参考资料

https://www.cnblogs.com/jlf0103/p/8882896.html

三、随机
3.1 随机抽取
import random
random.sample([1,2,3],3)
四、 目录

https://zhuanlan.zhihu.com/p/64893308

import sys
sys.path.append("..")  #在list中附加一个目录并查找
#引入路径导入包时,到达上级目录后,从上级目录的父目录开始from 。from可以是代码文件的名字,import 导入函数名
import xxx 

从…目录开始往下找

https://blog.csdn.net/universe_R/article/details/123370672

父级目录引入
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(root_dir)
os获取当前目录
# 使用os.walk扫描目录
import os

for curDir, dirs, files in os.walk("test"):
    print("====================")
    print("现在的目录:" + curDir)
    print("该目录下包含的子目录:" + str(dirs))
    print("该目录下包含的文件:" + str(files))
五、 注解
  1. 变量名后面加冒号仅仅是注解
def grayCode(self, n: int) -> List[int]:

->List[int]也是函数返回值的注释

六、 小数处理
保留小数
print("%.2f"%30)
np.around([0.37, 1.64], decimals=1)
七、 深拷贝和浅拷贝

从拷贝的实际程度而言,赋值<浅拷贝<深拷贝

https://blog.csdn.net/trochiluses/article/details/16879473

切片与工厂模式

obj=['name',['age',18]]
a=obj[:]
b=list(obj)
a属于切片,b属于工厂模式

字符串是重新创建,列表是引用

八、 元组

保护其内容不被外部接口修改

九、 可视化编程

http://pythontutor.makerbean.com/#mode=display

十、 for循环

给list每一个值都加1

https://zhidao.baidu.com/question/174221328.html (使用fo循环的形式)

十一、 链表

python的每一个对象都是指针,使用时都是在一个链表上进行的操作,所以画图看,很容易写出来的,用不同的指针指向不同的链表结点

十二、 enumerate
nums=[1,2,3,4]
for i, j in enumerate(nums):
    print(i,j)
结果为:
0,1
1,2
2,3
3,4
十三、Stack
a=[1,2,3,4]
a.append(5)
a.pop()
十四、 True 和False

python中true和false的定义
true使用大写字母开头,false也使用大写字母开头

a=[[0]*8]*8

这里修改一个值后全部进行了改变
在这里插入图片描述

十五、 类

python公有类和私有类

https://blog.csdn.net/vipshiwode/article/details/52778821?utm_source=blogxgwz1

十六、self

python单个类内方法的调用需要用self指定,self.

十七、set集合

python使用set集合, python不保证set集合的有序性

a=set()
a.add(1)
b.set()
b.add("k")
b.add("w")

https://blog.csdn.net/qq_35203425/article/details/100774387

set
内部实现是dict的python画树状图。在in操作上是O(1), 这一点比list要强。

https://blog.csdn.net/acbattle/article/details/97012800(list, set时间复杂度)

set返回有序

mailto = ['cc', 'bbbb', 'afa', 'sss', 'bbbb', 'cc', 'shafa']
addr_to = list(set(mailto))
print(addr_to)
addr_to.sort(key=mailto.index)
print(addr_to)
十八、 Queue队列

队列可以用list来进行描述

a=[1,2,3,4]
a.pop(0)

在pop时,使用pop(0)

十九、 排序
a=[3,2,1]
a.sort()
二十、 字典

给字典赋值默认值
在这里插入图片描述
注意下面的这个,可以通过这种方式给字典未知类型的变量不断赋值
在这里插入图片描述

https://blog.csdn.net/fzb1992/article/details/104305038

判断键值是否存在

dict={}
dict["a"]=1
dict["a"]=2
if dict["a"]!=None:
    dict["a"] += 1

字典的key值,字典的value值

dict.keys()
dict.values()

删除字典中的某一个键值对

a = {'数学': 95, '语文': 89, '英语': 90}
del a['语文']
del a['数学']
print(a)
对字典进行排序
dicts={"a":1,"b":3,"c":2}
sorted(dicts.items(), key=lambda x:x[1],reverse=True)
二十一、 list

python除了使用append()以外,可以使用[]+[],这样就不用pop了

list访问越界问题

list向后切片不越界
在这里插入图片描述

sorted按照某一列进排序

sorted(a_arr, key = lambda x:x[1]), 对于a_arr中,按照第一列排序

二十二、 时间复杂度

a=[1,2,3]
a.pop() 时间复杂度为O(1)
a.pop(0)时间复杂度为O(n)

https://www.cnblogs.com/lmygbl/articles/10183380.html

相关时间复杂度表

https://blog.csdn.net/coxhuang/article/details/90313828

a[::-1]

将def(a):
使用a=[a::-1]并不会修改a的值, 参考leetcode

https://leetcode-cn.com/problems/next-permutation/

如果去修改值,可以考虑使用a[:]=

sort函数

使用sort函数时,对于二维list,调用sort()函数,对每一行的第一个元素进行排序。

key值的使用

people = sorted(people, key = lambda x:(-x[0],x[1]))
负号表示降序,正号表示升序,先使用左边的进行排序,如果左边的相同,然后使用右边的进行排序。

https://www.cnblogs.com/Zioyi/p/13975036.html

二十三、 初始化为最大值

float(‘INF’)

二十四、红黑树

https://www.cnblogs.com/skywang12345/archive/2004/01/13/3245399.html

二十五、 yield的应用
def fuc(n):
    for i in range(10):
        yield i
for _ in fuc(3):
    print(_)

yield相当于把0到10之间的内容保存后做了一个返回。

二十六、 得到商和余数

divmod(n,10)可以得到商和余数

二十七、 Python字符串格式化符号及转义字符含义

https://blog.csdn.net/weixin_30326741/article/details/96724219

二十八、 filter函数

过滤掉得到符合条件的元素:

过滤出列表中的所有奇数:
def is_odd(n):
    return n % 2 == 1
 
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)

将二进制字符串转换为十进制
int(“111”,2)
将十进制转换为二进制
‘{0:b}’.format(2)
还可以使用
在这里插入图片描述

(0-1)%10 = 9,

二十九、 join函数的使用

在这里插入图片描述
以sep作为分隔符,将seq所有的元素合并成一个新的字符串

三十、 整除操作

//表示向左取整,3//2是1, 但是-3//2是-1

三十一、 pip 离线安装包

https://www.cnblogs.com/michael-xiang/p/5690746.html

pip的使用

https://blog.csdn.net/qq_15260769/article/details/80731407

装包遇到的问题

nltk包找不到, 注意文件夹的路径

https://blog.csdn.net/weixin_45910974/article/details/109485020?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-2&spm=1001.2101.3001.4242

三十二、 os库的使用
指定使用的显卡编号

import os
os.environ[‘CUDA_VISIBLE_DEVICES’]=‘1’

获取文件目录

https://www.cnblogs.com/wu-wu/p/11077016.html

三十三、记忆优化

用记忆化函数,保存出现过的 backtrack(s),避免重复计算。
在这里插入图片描述
在这里插入图片描述

三十四、 字符串

统计数字:
在这里插入图片描述
判断字符串是否为数字:
在这里插入图片描述
将字符转为ASCII码
ord(“a”)
在这里插入图片描述
将ASCII码转为字符
在这里插入图片描述

小写字母
在这里插入图片描述
是否是字母或者数字
在这里插入图片描述

三十五、 Input

https://blog.csdn.net/qq_39938666/article/details/101004633?utm_term=input%E8%BE%93%E5%85%A5%E5%A4%9A%E8%A1%8Cpython&utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2allsobaiduweb~default-2-101004633&spm=3001.4430

读取单行中的一个字符

line = int(input())

读取单行

line = input()
#然后按照split进行划分
line.split("" )
直走作用到map,转为自己想要的结果

行数未知

'多行输入,行数未知'
res = []
while True:
    try:
        s = input()
        # res.append(list(map(int, s.split(' '))))
        res.append(list(map(str, s.split(' '))))
    except:
        break
三十六、 try
try:
    int([1,2,3])
except:
    print("int不可以转化为a")
三十七、 map的使用

https://baijiahao.baidu.com/s?id=1594702528079035916&wfr=spider&for=pc

map
collections

https://blog.csdn.net/qq_36911138/article/details/103865008

map传多个参数
def fun(x,y=0):
    #print(x,y)
    return x,y
for each in map(fun, *zip([1,2],[3,4],[5,6])):
    print(each)
三十八、 打开文件
pkl文件的打开
import pickle
F=open(r'C:\blabala.pkl','rb')
content=pickle.load(F)
然后content就是原数据了。
正则表达式

https://www.cnblogs.com/nkwy2012/p/6548812.html
https://www.runoob.com/regexp/regexp-syntax.html(正则表达式符号详细解读)

三十九、 zip

https://www.cnblogs.com/waltsmith/p/8029539.html

字符串处理
过滤数字,字母等

https://www.jianshu.com/p/acf73e6f53a9

# ecoding=utf-8
ifn = r"train.txt"
ofn = r"train_output.txt"
infile = open(ifn,'rb')
outfile = open(ofn,'wb')
for eachline in infile.readlines():
  #去掉文本行里面的空格、\t、数字(其他有要去除的也可以放到' \t1234567890'里面)
  lines = filter(lambda ch: ch not in ' \t1234567890', eachline) 
  lines是一个filter,然后可以转为list后输出
  outfile.write(lines) # 写入train_output.txt(此处是一股脑的全写进去,并没有做任何的分行处理)
infile.close
outfile.close
open

w,w+的意思

https://www.cnblogs.com/nickkkk/p/8944772.html

将数据用追加的方式写入文件:

    f = open("./resdata/res.txt", "a+")
    f.write(res)
    f.write("\n")
打开文件
from reptiles import Google
import time

res = []
with open(u"train1.zh","r",encoding='utf-8') as f:
    while True:
        lines = f.readline()
        gg = Google()
        lines = gg.translate('zh-CN', 'ug', lines)[0]
        time.sleep(1)
        print(lines)
        if not lines:
            break
文件附加
from reptiles import Google
import time

res = []
index = 0
with open(u"train.zh","r",encoding='utf-8') as f:
    while True:
        lines = f.readline()
        if not lines:
            break
        gg = Google()
        lines = gg.translate('zh-CN', 'mn', lines)[0]
        index += 1
        print(index)
        if lines=="":
            continue
        with open("train.meng","a+",encoding='utf-8') as w:
            w.write(lines+"\n")
四十、 Timestamp

https://bbs.csdn.net/topics/392022982

a.timestamp()
文件路径
#获取当前文件夹所在的路径
os.listdir()
打印输出 (动态更新)
pytho -u 如果没有u,不会实时刷新
init

super(Net, self).init()
Python中的super(Net, self).init()是指首先找到Net的父类(比如是类NNet),然后把类Net的对象self转换为类NNet的对象,然后“被转换”的类NNet对象调用自己的init函数,其实简单理解就是子类把父类的__init__()放到自己的__init__()当中,这样子类就有了父类的__init__()的那些东西。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值