美文网首页
python练习1

python练习1

作者: _Irving | 来源:发表于2022-03-24 16:10 被阅读0次

    1、链式比较

    i=3
    print(1<i<3)  #False
    print(1<i<=3)#True
    

    2、不用else和if实现计算器

    from operator import  *
    def calculator(a,b,k):
        return {
            '+':add,
            '-':sub,
            '*':mul,
            '/':truediv,
            '**':pow
        }[k](a,b)
    
    print(calculator(1,2,'+')) #3
    print(calculator(8,4,'/')) #2.0
    

    3、求字符串的字节长度

    def str_byte_len(mystr):
        return (len(mystr.encode('utf-8')))
    
    print(str_byte_len('i love python')) #13
    

    4、寻找第n次出现的位置

    def search_n(s,c,n):
        size=0
        for i,x in enumerate(s):
            if x==c:
                size+=1
            if size==n:
                return i
        return -1
    print(search_n('hgfdsfhbsdbjfbsdjfnj','f',4))   #17
    print(search_n('hgfdsfhbsdbjfbsdjfnj','f',40))  #-1
    

    5、去掉最高最低求平均

    def score_mean(lst):
        lst.sort()
        lst2=lst[1:(len(lst)-1)]
        return round((sum(lst2)/len(lst2)),2)  #round返回浮点数的四舍五入值
    
    print(score_mean([9.1, 9.0,8.1, 9.7, 19,8.2, 8.6,9.8]))# 9.07
    

    6、打印乘法表

    def printnxn(n):
        for i in range(1,n+1):
            for j in range(1,i+1):
                # print("{}x{}={}\t".format(i,j,i*j),end=' ')
                print("%d x %d =%d \t"%(i,j,i*j),end=' ')
            print()
    printnxn(9)
    

    7、输出路径下以.html结尾的文件路径信息

    def print_html_dir(html_path):
        path_list=os.listdir(html_path)
        for i in path_list:
            path=os.path.join(html_path,i)
            if os.path.isdir(path):
                print_html_dir(path)
            if path.endswith(".html"):
                print(path)
    
    path=r"F:\测试\脚本\daily_test\analysis"
    print_html_dir(path)
    

    8、替换列表汇中所有的3为3a:

    num=['harden3','lam3pard',3,33,333,34,45,56,76,87,78,45,3,32,13,56,4231,7653,876,32]
    
    num_1=list(map(str,num))
    for index,i in enumerate(num_1,0):
        # if isinstance(i,basestring):
        if i.find('3')>=0:
            num_1[index]=num_1[index].replace('3','3a')
        elif i.isdigit():
            num_1[index]=int(num_1[index])
    print(num_1)
    

    9、合并去重

    list1=[2,3,4,6,8,9]
    list2=[1,2,5,4,6,9,11,15,21,23]
    list3=list1+list2
    print(list(set(list3)))
    

    10、#随机生成验证码

    import random
    list1=[]
    for i in range(65,91):
        list1.append(chr(i)) #通过for循环遍历asii追加到空列表中
    for j in range(97,123):
        list1.append(chr(j))
    for k in range(48,58):
        list1.append(chr(k))
    ma=random.sample(list1,6)
    ma=''.join(ma)
    print(ma)
    
    #2
    import string
    str1="0123456789"
    str2=string.ascii_letters
    str3=str1+str2
    ma1=random.sample(str3,6)
    ma1=''.join(ma1)
    print(ma1)
    

    11、判断闰年

    def if_runnian(year):
        if(year % 4)==0:
            if(year % 100)==0:
                if (year % 400)==0:
                    print("{0}是闰年".format(year))
                else:
                    print("{0}不是闰年".format(year)) #正百年不能被400整除的不是闰年
            else:
                print("{0}是闰年".format(year))  #非正百年能被4整除的为闰年
        else:
            print("{0}不是闰年".format(year))
    
    
    def if_runnian1(year):
        if (year % 4)==0 and (year%100)!=0 or (year%400)==0:
            print("{0}是闰年".format(year))
        else:
            print("{0}不是闰年".format(year))
    
    def if_runnian2(year):
        check_year= calendar.isleap(year)
        if check_year==True:
            print("%d是闰年"%year)
        else:
            print("%d是平年"%year)
    

    12、最大公约数

    def hcf(x,y):
       if x>y:
           smaller=y
       else:
           smaller=x
       for i in range(1,smaller+1):
           if (x%i==0) and (y%i==0):
               hcf=i
       return hcf
    

    13、最小公倍数

    def lcm(x,y):
        if x>y:
            greater=x
        else:
            greater=y
    
        while(True):
            if ((greater%x==0) and (greater%y==0)):
                lcm=greater
                break
            greater+=1
        return lcm
    

    14、嵌套数组完全展开

    def flatten(input_arr,output_arr=None):
        if output_arr is None:
            output_arr=[]
        for ele in input_arr:
            if isinstance(ele,Iterable):
                flatten(ele,output_arr)
            else:
                output_arr.append(ele)
        return output_arr
    
    print(flatten([[1,2,3],[4,5]], [6,7])) # [6, 7, 1, 2, 3, 4, 5]
    

    15、将list等分为子组

    from math import  ceil
    
    def divide(lst,size):
        if size<=0:
            return lst
        return [lst[i*size:(i+1)*size] for i in range(0,ceil(len(lst)/size))]
    
    r=divide([1,3,4,5,2,7,8,34,5],3) #[[1, 3, 4], [5, 2, 7], [8, 34, 5]]
    

    16、生成斐波拉茨序列的前n项

    def fibonacci(n):
        if n<=1:
            return [1]
        fib=[1,1]
        while len(fib)<n:
            fib.append(fib[len(fib)-1]+fib[len(fib)-2])
        return fib
    print(fibonacci(11))  #[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    

    17、出现最多元素

    def max_frequency(lst):
        return max(lst,default='列表为空',key=lambda v:lst.count(v))
    lst=[1,3,4,3,4,2,1,3,'a','a','a','a']
    print(max_frequency(lst))
    

    18、求列表中所有重复元素

    from collections import Counter
    
    def find_all_duplicates(lst):
        c = Counter(lst)   #Counter({3: 4, 2: 3, 1: 2})
        return list(filter(lambda k: c[k] > 1, c))   #k 为key值
    
    find_all_duplicates([1, 2, 2, 3, 3, 3])  # [2,3]
    

    19、字典值最大的键值对列表

    def max_pairs(dic):
        if len(dic) == 0:
            return dic
        max_val = max(map(lambda v: v[1], dic.items())) #返回的是(key,value)d的列表
        return [item for item in dic.items() if item[1] == max_val]
    
    max_pairs({'a': -10, 'b': 5, 'c': 3, 'd': 5})# [('b', 5), ('d', 5)]
    

    20、求字典钱n个最大值

    from heapq import nlargest
    
    def topn_dict(d,n):
        return nlargest(n,d,key=lambda k:d[k])   #主要是nlargest()函数的使用
    
    dic1={'a': 10, 'b': 8, 'c': 9, 'd': 10}
    print(topn_dict(dic1,2))
    

    21、查找指定文件格式文件

    import os
    def find_file(work_dir,extension='jpg'):
        lst=[]
        for filename in os.listdir(work_dir):
            splits=os.path.splitext(filename)  #返回的是(''test','.py')拆分扩展名
            ext=splits[1]
            if ext=='.'+extension:
                lst.append(filename)
        return lst
    print(find_file('.','py'))
    

    相关文章

      网友评论

          本文标题:python练习1

          本文链接:https://www.haomeiwen.com/subject/kiecjrtx.html