【Python基础】Python经典题目100道

文章目录

  • 前言
  • 初阶题目
  • 1.字符串
  • 2.列表
  • 3.元组
  • 4.字典
  • 5.运算
  • 6.random 模块
  • 7.open函数
  • 8.time模块时间
  • 9.其他
  • 进阶题目
  • 前言

    本文主要是python经典题目100题,适合入门的新手。仅作自己学习的记录。


    初阶题目

    1.字符串

  • 题目1:怎么找出序列中的最⼤最⼩值?
  • 方法:使用内置函数max()和min()。

    print(max([x for x in range(5)]))
    print(min([x for x in range(5)]))
    
    l=(233,456,445)
    print(max(l))
    print(min(l))
    
  • 题目2: 怎么将字符列表转为字符串?
  • 方法一:

    list1=['hello','world']
    str1=list1[0]
    str2=list1[1]
    
    print(str1+' '+str2)
    

    方法二: 使用join方法,合并序列的元素,推荐!!!

    功能:join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
    语法:string.join()

    list1=['hello','world']
    str1=' '.join(list1)
    print(str1)
    
  • 题目3:怎么快速打印出包含所有 ASCII 字⺟(⼤写和⼩写)的字符串?
  • import string
    string.ascii_letters
    
  • 题目4: 怎么让字符串居中?
  • 方法:使用字符串中的center方法。

    功能:返回一个指定宽度width居中的字符串,length为所返回字符串的长度。fillchar为填充的字符,默认为空格。
    语法:string.center(length, character)

    str1='hello'
    str1.center(50)
    str1.center(50,'###')
    
  • 题目5:怎么在字符串中找到⼦串?
  • 方法:使用find方法。

    功能:检测字符串中是否包含子字符串 str 。如果找到,就返回子串的第一字符的索引值,如果找不到,则返回-1。
    语法:string.find(value,start,end)

    str1='hello world'
    str1.find('h')
    str1.find('w')
    
  • 题目6:怎么让字符的⾸字⺟⼤写,其他字⺟⼩写?
  • 方法一:使用title方法。

    功能:所有单词的首个字母转化为大写,其余字母均为小写。
    语法:string.title()

    str1='hello world'
    str1.title()
    

    方法二:使用capwords方法

    import string
    str1='hello world'
    string.capwords(str1)
    
  • 题目7:怎么批量替换字符串中的元素?
  • 方法一:使用replace()方法。

    str1="hello"
    str1.replace('l','w')
    

    方法二:使用re模块的sub方法。

    import re 
    str1="hello"
    re.sub('l','w',str1)
    
  • 题目8:怎么把字符串按照空格进⾏拆分?
  • 方法一:使用split方法,括号为空的情况下默认为空格拆分 。

    str1="hello world hello"
    str1.split()
    

    方法二:使用re模块下的split方法。

    str1="hello world hello"
    import re
    re.split(r'\s+',str1)
    
  • 题目9:怎么去除字符串⾸位的空格?
  • 方法:用strip方法

    str1=" hello world "
    str1.strip()
    

    2.列表

  • 题目10:怎么清空列表内容?
  • 方法一:使用del方法清除整个列表,删除后表不存在了。

    list1=[x for x in range(5)]
    del list1
    

    方法二:使用clear方法,删除后表为空。

    list1=[x for x in range(5)]
    list1.clear()
    

    方法三:使用切片赋值方法,删除后表为空。

    list1=[x for x in range(5)]
    list1[:]=[]
    list1
    
  • 题目11:怎么计算指定的元素在列表中出现了多少次?
  • 方法:使用count方法。

    list1=[x for x in np.random.randint(40,90,10)]
    list1.count(40)
    
  • 题目12:怎么在列表末尾加⼊其它元素?
  • 方法:使用extend方法。

    list1=[x for x in range(5)]
    list2=[x for x in np.random.randint(1,10,3)]
    list1.extend(list2)
    
  • 题目13:extend 和列表相加的区别?
  • 两者效果看起来是一致的,但是extend是直接在list1列表里加入元素,相加会生成一个新的列表,list1本质没有改变。

  • 题目14:怎么查找列表中某个元素第⼀次出现的索引,从 0 开始?
  • list1=[x for x in range(1,5)]
    list1.index(3)
    
  • 题目15:怎么将⼀个对象插⼊到列表中?
  • 方法一:使用append方法。在最后插入一个对象。

    list1=[x for x in range(1,5)]
    list1.append(6)
    

    可以指定元素位置后插入。

    方法一:使用insert方法。

    list1=[x for x in range(1,5)]
    list1.insert(2,6)
    

    方法二:使用切片方法。

    list1=[x for x in range(1,5)]
    list1[2:2]=['hello']
    
  • 题目16:怎么删除列表中元素?
  • 方法:使用pop方法。

    删除单个元素,按位删除(根据索引删除),默认为列表对象最后一个元素,list.pop(i)则删除下标为i的元素,删除时会返回被删除的元素。

    list1=[x for x in range(10)]
    list1.pop[3]
    
  • 题目17:怎么删除列表中指定元素?
  • 方法:使用remove方法,删除第一次出现的元素。

    list1=[x for x in range(10)]
    list.remove(5)
    
  • 题目18:怎么让列表按相反顺序排列?
  • 方法一:使用reverse方法。

    list1=[x for x in range(10)]
    list1.reverse()
    

    方法二:使用切片的方式。

    list1=[x for x in range(10)]
    list1[::-1]
    

    3.元组

  • 题目19:怎么表示只包含⼀个元素的元组?
  • 1个元素的元组,必须在唯一的元素后面加上逗号。

    tup1=('hello',)
    print(type(tup1))
    

    4.字典

  • 题目20:怎么给字典中不存在的key指定默认值?
  • 方法一

    dic1={"a":"hell0","b":"world"}
    dic1.get('aa','N/A')
    

    方法二

    dic1={"a":"hell0","b":"world"}
    dict1["c"]="mary"
    dict1
    

    参考链接:https://www.runoob.com/python/att-dictionary-get.html

  • 题目21:花括号{} 是集合还是字典?
  • 字典

    type({})
    

    5.运算

    基本运算

  • 题目22:怎么计算2的3次⽅?
  • 方法一:使用运算符**。

    print(2**3)
    

    方法二: 用pow()函数,pow(x,y)返回 x 的 y 次方的值

    print(pow(2,3))
    
  • 题目23:怎么快速求 1 到 100 所有整数相加之和?
  • 方法一:使用sum方法

    print(sum(range(1,101)))
    

    方法二:使用while方法

    a=0
    b=0
    while a<100:
    	a=a+1
    	b=b+a
    
    print(b)
    

    方法三:使用for方法

    a=0
    for i in range(1,101):
    	a=a+i
    	
    print(a)
    

    集合运算

  • 题目24:怎么求两个集合的并集?
  • 方法一:使用union方法。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1.union(set2))
    

    方法二:使用运算符 | 。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1|set2)
    
  • 题目25:求两个集合的交集?
  • 方法一:使用运算符 & 。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1&set2)
    

    方法二:使用intersection方法。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1.intersection(set2))
    
  • 题目26:求两个集合中不重复的元素?
  • 方法一:使用运算符 ^ 。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1^set2)
    

    方法二:使用 symmetric_difference 方法。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1.symmertric_differece(set2))
    
  • 题目27:求两个集合的差集?
  • 方法一:使用运算符 – 。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1-set2)
    

    方法二:使用differece方法。

    set1={"a","b","c","d","e","f"}
    set2={"a","b","c","d","g","h"}
    print(set1.differece(set2))
    

    6.random 模块

  • 题目28:怎么从⼀个⾮空序列中随机选择⼀个元素?
  • 方法:使用random中的choice方法。

    import random 
    list1=[x for x in range(1,10)]
    random.choice(list1)
    
  • 题目29:从⼀个序列中随机返回 n 个不同值的元素?
  • 方法:使用random中sample方法。

    import random 
    list1=[x for x in range(10,100)
    sample_num=5
    random.sample(list1,sample_num)
    
  • 题目30:怎么⽣成两个数之间的随机实数?
  • 方法一:使用random.randint()生成随机整数

    import random 
    random.randint(1,100)
    

    方法二:使用random.uniform()生成随机的浮点数

    import random 
    random.uniform(1,100)
    
  • 题目31:怎么在等差数列中随机选择⼀个数?
  • 方法一:使用random.choice()方法。

    import random 
    random.choice([x for x in range(1,100,10)])
    

    方法二:使用用random.randrange()可以指定步长。

    import random 
    random.randrange(0,100,10)
    
  • 题目32:怎么随机打乱列表的顺序?
  • 方法:使用random模块里的shuffle方法。

    import random 
    list1=[x for x in range(10)]
    print(list1)
    random.shuffle(list1)
    print(list1)
    

    参考链接:https://blog.csdn.net/m0_46090675/article/details/113818633

    7.open函数

  • 题目33:怎么在⽂件⾥写⼊字符?
  • 方法:用open函数,模式用w。

    file_path=""
    content="hello world"
    
    with open(file_path,'w') as file:
    	file.write(content)
    
  • 题目34:怎么读取⽂件内容?
  • 方法:用open函数,模式用r(默认情况下是r)。

    file_path=""
    with open(file_path,"r",encoding="utf-8") as f:
    	res=f.read()
    	print(res)
    

    8.time模块时间

  • 题目35:怎么将当前时间转为字符串?
  • 方法一:使用time模块里的asctime方法。若未输入参数,返回当前时间字符串的形式。

    import time
    time.asctime()
    print(type(time.asctime()))
    

    方法二:使用datetime下面的strftime方法。

    import datetime
    time1=datetime.datetime.now()
    print(time1)
    print(type(time1))
    
    time2=time1.strftime('%Y-%m-%d %H:%M:%S')
    print(time2)
    print(type(time2))
    
  • 题目36:怎么将秒数转为时间数组?
  • 方法:使用time模块里面的localtime方法。

    import time
    seconds = 1555840541.92
    timeArray = time.localtime(seconds)
    print(timeArray)
    
  • 题目37:将时间元组转换为从新纪元后的秒数?
  • 方法:使用time模块里面的mktime方法。

    import time
    time.mktime((2023,11,6,17,14,48,1,311,0))
    
  • 题目38:怎么将字符串转为时间元组?
  • 方法:使用time模块里的strptime方法。

    import time 
    time.strptime('2023-11-23', '%Y-%m-%d')
    

    9.其他

  • 题目39:怎么查出模块包含哪些属性?
  • 方法:使用dir()函数查看模块的属性与方法

    dir(str)
    
  • 题目40:怎么快速查看某个模块的帮助⽂档?
  • 方法:使用__doc__查看某个模块下面的注释的内容。

    str.__doc__
    
  • 题目41:怎么快速启动浏览器打开指定⽹站?
  • 方法:使用webbrowser

    import webbrowser
    
    path = "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
    
    webbrowser.register('edge', None, webbrowser.BackgroundBrowser(path))
    browser = webbrowser.get('edge')
    browser.open('www.baidu.com')
    

    参考链接:https://blog.csdn.net/wangyuxiang946/article/details/132231956

  • 题目42:Python⾥占位符怎么表示?
  • 用pass占位,当你没有想好代码块的逻辑时,你需要运行代码调试其他功能,需要加占位符,不然会报错。

    if name="lily":
    	print("hello")
    elif name="mary":
    	pass
    
  • 题目43:怎么给函数编写⽂档?
  • 在def语句后面注释文档放在引号(单引、双引、三引都可以)里面就行,文档可以通过func1.__doc__访问。

    def func1():
    	"""返回变量值"""
    	x="hello world"
    	return x
    
    func1.__doc__
    
  • 题目44:怎么定义私有⽅法?
  • 定义:私有方法是指只能在类内调用。
    语法:在方式名称前加两个斜杠__
    注意:⽤ from module import * 导⼊时不会导⼊私有⽅法

    class Dog():
    	def __init__(self,age,color,name='lily'):
    		self.name=name
    		self.age=age
    		self.color=color
    	def __hello(self):
    		print("我的名字是{},我{}岁了".format(self.name,self.age))
    		
    x=Dog(5,'yellow')
    x.__hello() ##报错
    x._Dog__hello()
    
  • 题目45:怎么判断⼀个类是否是另⼀个类的⼦类?
  • 方法一:使用内置函数 issubclass()

    语法:issubclass(class, classinfo),class是待检查的类,classinfo是一个类或一个由类对象组成的元组。如果class是classinfo的子类或者是classinfo中的任意类的子类,则返回True;否则返回False。

    class Father():
    	pass
    class Son(Father):
    	pass
    
    print(issubclass(Father,Son))
    print(issubclass(Son,Father))
    

    方法二:使用内置函数isinstance()

    语法:isinstance(object, classinfo),object是待检查的对象,classinfo是一个类或一个由类对象组成的元组。如果object是classinfo的实例或者是classinfo中的任意类的实例,则返回True;否则返回False。

    class Father():
    	pass
    class Son(Father):
    	pass
    
    print(isinstance(Father,Son))
    print(isinstance(Son,Father))
    
  • 题目46:怎么查出通过 from xx import xx导⼊的可以直接调⽤的⽅法?
  • 方法:使用all方法,这个方法查出的是模块下不带_的所有方法,可以直接调用。

    import random
    random.__all__
    
  • 题目47:怎么把程序打包成 exe ⽂件?
  • 方法:⽤ Setuptools ⾥的 py2exe 库

  • 题目48:怎么把程序打包称 Mac 系统可运⾏的 .app ⽂件?
  • 安装py2app

    pip install py2app
    

    cd 到demo.py文件所在的目录
    py2applet –make-setup demo.py

  • 题目49:怎么获取路径下所有⽬录名称?
  • 方法:使⽤ sys 下的 path ⽅法,返回的是⽬录名称的字符串列表。

    import sys
    sys.path
    
  • 题目50:Python 环境下怎么执⾏操作系统命令?
  • ⽅法:使⽤ os 模块下的 system ⽅法。

    import os 
    os.system("cd /User/")
    

    进阶题目

  • 题目51:怎么⽤for循环实现把字符串变成Unicode码位的列表?
  • 方法:ord(c)函数,c表示字符,返回值是对应的十进制整数。

    str="hello world"
    list1=[]
    for i in str:
    	list1.append(ord(i))
    print(list1)
    
    ##输出:
    [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
    
  • 题目52:怎么⽤列表推导式实现把字符串变成Unicode码位的列表?
  • str="hello world"
    [ord(x) for x in str]
    
    ##输出:
    [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
    
  • 题目53:打印出两个列表的笛卡尔积?
  • 方法一:使用for循环。

    list1=[x for x in range(1,5)]
    list2=['a','b','c']
    for tshirt in ('%s %s'%(c,s) for c in list1 for s in list2):
        print(tshirt) 
        
    # 输出:
    1 a
    1 b
    1 c
    2 a
    2 b
    2 c
    3 a
    3 b
    3 c
    4 a
    4 b
    4 c
    

    方法二:使用itertools里的product生成器函数。

    import itertools
    list1=[x for x in range(1,5)]
    list2=['a','b','c']
    result=list(itertools.product(list1,list2))
    
    # 输出:
    [(1, 'a'),
     (1, 'b'),
     (1, 'c'),
     (2, 'a'),
     (2, 'b'),
     (2, 'c'),
     (3, 'a'),
     (3, 'b'),
     (3, 'c'),
     (4, 'a'),
     (4, 'b'),
     (4, 'c')]
    
  • 题目54:可迭代对象拆包时,怎么赋值给占位符?
  • 方法: 用for循环提取元组里的元素,对于我们不想接收的元素,我们可以用占位符 _ 接收。

    tuple_infos=[('lily','24'),('James','30'),('mary','45')]
    
    for names,_ in tuple_infos:
    	print(names)
    
    # 输出:
    lily
    James
    mary
    
  • 题目55:Python3 中,⽤什么⽅式接收不确定值或参数?
  • 方法:*args位置可以在任意位置。

    a,b,*c=range(8)
    a,b,c
    # 输出:(0, 1, [2, 3, 4, 5, 6, 7])
    
    a,*b,c,d=range(5)
    a,b,c,d
    # 输出:(0, [1, 2], 3, 4)
    
    *a,b,c,d=range(5)
    a,b,c,d
    # 输出:([0, 1], 2, 3, 4)
    

    参考链接:https://blog.csdn.net/sodaloveer/article/details/134165294

  • 题目56:⽤切⽚讲对象倒序?
  • list1=[x for x in range(1,10)]
    list1[::-1]
    # 输出:[9, 8, 7, 6, 5, 4, 3, 2, 1]
    
  • 题目57:怎么查看列表的 ID?
  • 方法:使用id函数。

    l=[1,2,3]
    id(l)
    # 输出:2370660297728
    
  • 题目58:可变序列⽤*=(就地乘法)后,会创建新的序列吗?
  • 不会。可变序列用*=后,不会创建新的序列,新元素追加到老元素之上,新老列表的id是相等的。

    a=[1,2,3]
    print('旧列表的id:',id(a))
    
    a*=2
    print("*=(就地乘法)后列表:",a)
    print('旧元组的id:',id(a))
    
    # 输出:
    # 旧列表的id: 1554734688192
    # *=(就地乘法)后列表: [1, 2, 3, 1, 2, 3]
    # 旧元组的id: 1554734688192
    

    按序列能否被修改,可以将python序列分为可变和不可变序列。
    可变序列:可以进行增、删、改等操作序列。比如:列表、集合。
    不可变序列:元组、字符串。

  • 题目59:不可变序列⽤*=(就地乘法)后,会创建新的序列吗?
  • 会,不可变序列用*=后,会创建新的序列,看下面的例子,新老元组的id是不同的。

    t=(1,2,3)
    print('旧元组的id:',id(t))
    
    t*=2
    print("*=(就地乘法)后元组:",t)
    print('旧元组的id:',id(t))
    
    # 输出:
    # 旧元组的id: 1554729209600
    # *=(就地乘法)后元组: (1, 2, 3, 1, 2, 3)
    # 旧元组的id: 1554729054272
    

    注意: 对不可变序列进行重复拼接操作的话,效率会很低,因为每次都有一个新对象,而解释器需要把原来对象中的元素先复制到新的对象里,然后再追加新的元素。

    关于序列相关应用参考:https://zhuanlan.zhihu.com/p/33488349

  • 题目60:关于+=的⼀道谜题。
  • t=(1,2,[10,20])
    t[2]+=[50,60]
    

    到底会发生下面4种情况中的哪一种?
    a. t会变成(1, 2, [10, 20, 50, 60])。
    b. 因为tuple不支持对它的元素赋值,所以会出现TypeError异常。
    c. 以上两个都不是。
    d. a和b都是对的。

    t
    # 输出:
    (1, 2, [10, 20, 50, 60])
    

    答案是d。

  • a+=b 和 a.extend(b) 一样的效果。
  • list1=[x for x in range(10)]
    list1+=[20,30] # 输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30]
    list1.extend([20,30]) # 输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 20, 30]
    
  • 题目61:sort() 和 sorted() 区别?
  • 1、sort 是应用在list上的方法,属于列表的成员方法;sorted可以对所有迭代的对象进行排序操作。
    2、list的sort方法返回的是对已经存在的列表进行操作,而内建函数sorted方法返回的是一个新的list,而不是在原来的基础上进行的操作。
    3、sort使用方法为list.sort(),sorted使用方法为sorted(list)。

    list1=[1,100,90,23]
    list1.sort()
    print(list1)
    # 输出:
    # [1, 100, 90, 23]
    
    list1=[1,100,90,23]
    list3=sorted(list1)
    print(list1,'\n',list3)
    # 输出:
    # [1, 100, 90, 23] 
    # [1, 23, 90, 100]
    

    参考链接:https://blog.csdn.net/u013759354/article/details/80243705

  • 题目62:怎么通过 reverse 参数对序列进⾏降序排列?
  • reverse参数一般放在sorted()方法里面,reverse默认值为False,序列默认升序排列,降序排列的话需要将reverse的值设置为True。

    list1=[1,100,90,23]
    list2=sorted(list1,reverse=True)
    print(list2)
    # 输出:
    # [100, 90, 23, 1]
    

    参考链接:https://blog.csdn.net/qq_27003337/article/details/104974498

  • 题目63:numpy 怎么把⼀维数组编程⼆维数组?
  • 方法一:直接操作shape属性。

    import numpy as np
    a=np.arange(6)
    
    a.shape
    # 输出:
    # (6,)
    
    a.shape=(2,3)
    a
    # 输出:
    # array([[0, 1, 2],
    #       [3, 4, 5]])
    

    方法二:利用np.reshape()。

    import numpy as np
    a=np.arange(6)
    
    a.shape
    # 输出:
    # (6,)
    
    a
    # 输出:
    # array([0, 1, 2, 3, 4, 5])
    
    np.reshape(a,(2,3)).shape
    # 输出:
    # (2, 3)
    

    参考链接:https://www.zhihu.com/question/59563149

  • 题目64:快速插⼊元素到列表头部?
  • 方法一:利用切片。

    list1=[x for x in range(1,5)]
    list1[0:0]='hello'
    list1
    
    # 输出:
    # ['h', 'e', 'l', 'l', 'o', 1, 2, 3, 4]
    

    方法二:超低频insert()方法插入,第一参数是位置的坐标,从0开始。

    list1=[x for x in range(5)]
    list1.insert(0,'first')
    list1
    ['first', 0, 1, 2, 3, 4]
    

    方法三:利用deque类。
    在第一个元素之前添加一个元素之类的操作是很耗时的,因为这些操作会牵扯到移动列表里的所有元素。
    利用deque类可以更高效,deque类可以指定这个队列的大小, 如果这个队列满员了,还可以从反向端删除过期的元素,然后在尾端添加新的元素。

    from collections import deque
    dp=deque(range(10),maxlen=15)
    dp
    # 输出:
    # deque([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    
    dp.appendleft(-1)
    dp
    # 输出:
    # deque([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    
  • 题目65:字典的创建⽅法?
  • 方法一:直接创建。

    dict1={'a':1,'b':2,'c':3}
    dict2=dict(zip('abc','123'))
    
    dict3=dict(a=1,b=2,c=3)
    dict4=dict([('a',1),('b',2),('c',3)])
    

    方法二:用字典推导构建字典。

    dial_code=[(1,'a'),(2,'b'),(3,'c')]
    coutry_code = {coutry:code for code, coutry in dial_code}
    coutry_code 
    # 输出:
    # {'a': 1, 'b': 2, 'c': 3}
    
  • 题目66:通过⼀次查询给字典⾥不存的键赋予新值?
  • 方法一:用setdefault方法只查询一次效果更快。

    dict1={'a':1,'b':2,'c':3}
    dict1.setdefault('d',[]).append(4)
    dict1
    # 输出:
    # {'a': 1, 'b': 2, 'c': 3, 'd': [4]}
    

    方法二:用if方法,要查询三次。

    dict1={'a':1,'b':2,'c':3}
    if 'd' not in dict1.keys():
    	dict1['d']=[]
    	dict1['d'].append(4)
    print(dict1)
    # 输出:
    # {'a': 1, 'b': 2, 'c': 3, 'd': [4]}
    

    在python3中dict.keys()的返回值是一个“视图”,视图就像一个集合,跟字典类似的,在视图里查找一个元素的速度很快。

  • 题目67:怎么统计字符串中元素出现的个数?
  • 方法:用collections中的Counter方法统计,返回的结果是对应元素和个数形成的键值对。

    import collections
    str1="hello hello hello world"
    ct=collections.Counter(str1)
    ct
    
    # 输出:
    # Counter({'h': 3, 'e': 3, 'l': 7, 'o': 4, ' ': 3, 'w': 1, 'r': 1, 'd': 1})
    
  • 怎么统计出排名前n的元素?
  • 方法:用most_common方法,比如前两名的话,n=2。

    ct.most_common(2)
    
    # 输出:
    # [('l', 7), ('o', 4)]
    
  • 题目68:列表去重?
  • 方法一:用for循环进行遍历。

    list1=[1,11,1,1,8,2]
    list2=[]
    for x in list1:
    	if x not in list2:
    		list2.append(x)
    print(list2)	
    # 输出:
    # [1, 11, 8, 2]
    

    方法二:利用set自动去重功能。

    list1=[1,11,1,1,8,2]
    list2=list(set(list1))
    print(list2)
    # 输出:
    # [1, 11, 8, 2]
    

    方法三:利用set+索引,可以保证去重后的顺序不变。

    list1=[1,11,1,1,8,2]
    list2=list(set(list1))
    list2.sort(key=list1.index)
    # 输出:
    # [1, 11, 8, 2]
    

    参考链接:https://blog.csdn.net/JohinieLi/article/details/81182771

  • 题目69:求m中元素在n中出现的次数?
  • 方法一:基础求法。

    m=['a','b','c']
    n=['a','b','c','d','e']
    
    find=0
    for i in m:
    	if i in n:
    		find+=1
    		
    print(find)
    # 输出:3
    

    方法二:用集合取交集

    m=['a','b','c']
    n=['a','b','c','d','e']
    
    len(set(m)&set(n)) # 输出:3
    
    len(set(m).intersection(n)) # 输出:3
    

    如果m和n不是集合,直接转换后再取交集。

  • 题目70:新建⼀个Latin-1字符集合,该集合⾥的每个字符的Unicode名字⾥都有“SIGN”这个单词,⽤集合推导式完成。
  • from unicodedata import name
    {chr(i) for i in range(32,256) if 'SIGN' in name(chr(i),'')}
    
    # 输出:
    {'#',
     '$',
     '%',
     '+',
     '<',
     '=',
     '>',
     '¢',
     '£',
     '¤',
     '¥',
     '§',
     '©',
     '¬',
     '®',
     '°',
     '±',
     'µ',
     '¶',
     '×',
     '÷'}
    
  • 题目71:查询系统默认编码⽅式?
  • 方法一:sys.getdefaultencoding()方法。

    import sys
    sys.getdefaultencoding() # 输出:'utf-8'
    

    方法二

    fp=open('test.txt','w')
    fp.encoding # 输出:'utf-8'
    
  • 题目72:修改编码⽅式?
  • 方法一:sys.setdefaultencoding()方法。

    import sys
    sys.setdefaultencoding('utf-8') 
    

    方法二

    fp=open('test.txt','w',encoding='utf-8')
    fp.encoding
    
  • 题目73:⽤递归实现阶乘?
  • 5=5*4*3*2*1
    4=4*3*2*1 这种形式叫做阶乘

    递归:一个函数自己调用自己。

    def getNum(num):
    	if num>1:
    		return num * getNum(num-1)
    	else:
    		return num 
    
    def factorial(n):
    	"""return n!"""
    	return 1 if n<2 else n*factorial(n-1)
    
  • 题目74:all([])的输出结果是多少?
  • 方法:all()函数用于判断给定的可迭代参数iterable中的所有元素是否为True,如果是返回True,否则返回False。
    元素除了是0,空,None,False外都算True。

    all([])
    # 输出:True
    

    注意:空元组、空列表返回值都为True。

  • 题目75: any([])的输出结果是多少?
  • 方法:any()用于判断给定的可迭代参数iterable是否全部为False,则返回False,如果有一个为True,则返回True。

    any([])
    # 输出:False
    
  • 题目76:怎么判断对象是否可被调⽤?
  • 方法一:使用内置的callable函数。
    callable(func),用于检查对象是否可调用,返回True也可能调用失败,但是返回False一定不可调用。

    [callable(obj) for obj in (abs,str,2)]
    # 输出:[True, True, False]
    

    方法二:判断对象类型是否是FunctionType。
    (from types import FunctionType)

  • 方式一:type(func) is FunctionType
  • 方式二:isinstance(func,FunctionType)
  • def func1():
    	return 1
    
    from types import FunctionType
    [type(obj) is FunctionType for obj in (func1,str,2)] # 输出:[True, False, False]
    isinstance(func1,FunctionType) # 输出:True
    

    方法三:判断对象是否实现__call__方法。
    hasattr(func,‘call’)

    [hasattr(obj,'__call__') for obj in (abs,str,2)] # 输出:[True, True, False]
    

    参考链接:https://blog.csdn.net/sinat_38682860/article/details/105074130

  • 题目77:怎么列出对象的所有属性?
  • 方法:使用dir()函数。

    import sys
    dir(sys)
    
  • 题目78:怎么得到类的实例没有函数⽽有属性的列表?
  • 方法:创建一个空的用户定义的类和空的函数,计算差集,让后排序。

    class C:
    	pass
    	
    obj=C()
    def func():
    	pass
    
    sorted(set(dir(func))-set(dir(obj)))
    
     # 输出:
    ['__annotations__',
     '__call__',
     '__closure__',
     '__code__',
     '__defaults__',
     '__get__',
     '__globals__',
     '__kwdefaults__',
     '__name__',
     '__qualname__']
    
  • 题目79:函数中,不想⽀持数量不定的定位参数,但是想⽀持仅限关键字参数,参数怎么定义?
  • 方法:在关键字参数前加一个*。

    def func1(a,*,b):
    	return a,b
    func1(1,b='hello')
    
    #输出:
    #(1, 'hello')
    
  • 题目80:怎么给函数参数和返回值注解?
  • 代码执行时,注解不会做任何处理,只是存储在函数_annotations__属性(一个字典)中。

    函数声明中的各个参数可以在:之后增加注解表达式,如果参数有默认值,注解放在参数名和=号之间,如果想注解返回值,在)和函数声明末尾的:之间添加->和一个表达式。

    def function(text:str,max_len:"int>0"=80) -> str:
    
  • 题目81:不使⽤递归,怎么⾼效写出阶乘表达式?
  • 方法:通过reduce和operator.mul函数计算阶乘

    from functools import reduce
    from operator import mul
    def fact(n):
    	return reduce(mul,range(1,n+1))
    
    fact(5)
    
  • 题目82:Python什么时候执⾏装饰器?
  • 函数装饰器在导入模块时立即执行,而被装饰的函数只在明确调用时运行,这突出了python程序员所说的导入时和运行时之间的区别。

  • 题目83:判断下⾯语句执⾏是否会报错?
  • b=3
    def func(a):
    	print(a)
    	print(b)
    	b=7
    
    func(1)
    

    会报错,python编译函数的定义体时 ,先做了一个判断 ,那就是b是局部变量,因为在函数中给它赋值了,但是执行print(b)时,往上又找不到b的局部值,所以会报错。

  • 题目84:怎么强制把函数中局部变量变成全局变量?
  • 如何理解局部变量与全部变量,请参考:https://blog.csdn.net/sodaloveer/article/details/132988232

    方法:用global声明

    b=3
    def func(a):
    	global b
    	print(a)
    	print(b)
    	b=7
    	
    b=10
    func(3)
    
    # 输出:
    3
    10
    
  • 题目85:闭包中,怎么对数字、字符串、元组等不可变元素更新?
  • 方法:nonlocal声明,把变量标记为自由变量。

    def func1():
        a=1
        b=2
        def func2(c):
            a+=1
            b+=c
            return a/b
        return func2
    
    result=func1()
    result(10)
    
    # 报错:UnboundLocalError: local variable 'a' referenced before assignment
    
    def func1():
        a=1
        b=2
        def func2(c):
            nonlocal a,b
            a+=1
            b+=c
            return a/b
        return func2
    
    result=func1()
    result(10)
    
    # 输出:
    0.16666666666666666
    
  • 题目86:测试代码运⾏的时间?
  • 方法一:time模块里的perf_counter方法。

    import time
    t0=time.perf_counter()
    for i in range(10000):
    	pass
    	
    t1=time.perf_counter()
    t1-t0 # 输出:0.0003746999973373022
    

    方法二:time.time()

    import time 
    t0=time.time()
    for i in range(10000):
    	pass
    	
    t1=time.time()
    t1-t0 # 输出:0.0009982585906982422
    
  • 题目87:怎么优化递归算法,减少执⾏时间?
  • 方法:使用装饰器 functools.lru_cache()缓存数据

    import functools 
    @functools.lru_cache()
    
    def fibonacci(n):
    	if n<2:
    		return n 
    	return fibonacci(n-2)+fibonacci(n-1)
    	
    fibonacci(6) # 输出:8
    
  • 题目88:⽐较两个对象得值(对象中保存的数据)是否相等?
  • 方法:用 == 运算符比较

    a=[1,2,3]
    b=[1,2,3]
    a==b # 输出:True
    
  • 题目89:⽐较两个对象得内存地址 id 是否相等?
  • 方法:用is比较,id一定是唯一的数值标注,而且在对象的生命周期中绝对不会变

    a=[1,2,3]
    b=[1,2,3]
    a is b # 输出:False
    
  • 题目90:怎么格式化显示对象?
  • 方法:
    format(my_obj,format_spec)的第二个参数
    str.format()方法,{}里代换字段中置换后面的部分。

    print('{:.2%}'.format(0.25)) # 输出:25.00%
    

    参考链接:https://blog.csdn.net/sodaloveer/article/details/134133286

  • 题目91:复制⼀个序列并去掉后 n 个元素。
  • 方法:利用切片思想。

    list1=[x for x in range(5)]
    list2=list1[:-2] # 输出:[0, 1, 2]
    
  • 题目92:Python中怎么定义私有属性。什么叫私有属性?
  • 在属性前加两个前导下划线,尾部没有或最多有一个下划线。

  • 题目93:怎么随机打乱⼀个列表⾥元素的顺序?
  • 方法:用random里的shuffle方法

    from random import shuffle
    l=list(range(30))
    shuffle(l)
    l
    
  • 题目94:怎么判断某个对象或韩式是⼀个已知的类型?
  • 方法:用python的内置函数isinstance()判断

    isinstance('aa',str) # 输出:True
    
  • 题目95:怎么打印出分数?
  • 方法:用fractions中的Fraction方法

    from fractions import Fraction
    print(Fraction(1,3)) # 输出:1/3
    
  • 题目96:+ 和 += 区别?
  • 方法:两边必须是同类型的对象才能相加,+=右操作数往往可以是任何可迭代对象。

    list1=[x for x in range(6)]
    list1+='gwer'
    list1 # 输出:[0, 1, 2, 3, 4, 5, 'g', 'w', 'e', 'r']
    
    list2=list1+(6,7)
    #报错:TypeError: can only concatenate list (not "tuple") to list
    
  • 题目97:怎么列出⼀个⽬录下所有的⽂件名和⼦⽂件名?
  • 方法:使用os模块下面的walk,返回一个生成器,该生成器创建一个值元组(current_path,current_path中的目录,current_path中的文件)
    os.listdir(path)列出一个目录下面的所有目录与文件名。

    import os 
    dirs=os.walk("F:\\python_test")
    for dir in dirs:
    	print(dir)
    
  • 题目98:怎么返回 1 到 10 的阶乘列表?
  • import itertools
    import operator
    list(itertools.accumulate(range(1,11),operator.mul))
    # 输出:[1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
    
  • 题目99:怎么快速拼接字符串和序列形成新的列表?
  • 方法:用itertools里的chain方法。

    import itertools
    list(itertools.chain('ABC',range(5)))
    # 输出:['A', 'B', 'C', 0, 1, 2, 3, 4]
    
  • 题目100:进度条显示?
  • 方法:用tqdm库

    import time
    from tqdm import tqdm 
    for i in tqdm(range(1000)):
    	time.sleep(.01)
    

    作者:sodaloveer

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【Python基础】Python经典题目100道

    发表回复