• 吴裕雄--天生自然python编程:实例(1)


    str = "www.runoob.com"
    print(str.upper())          # 把所有字符中的小写字母转换成大写字母
    print(str.lower())          # 把所有字符中的大写字母转换成小写字母
    print(str.capitalize())     # 把第一个字母转化为大写字母,其余小写
    print(str.title())          # 把每个单词的第一个字母转化为大写,其余小写 

    import calendar
    monthRange = calendar.monthrange(2016,9)
    print(monthRange)

    # 引入 datetime 模块
    import datetime
    
    def getYesterday(): 
        today=datetime.date.today() 
        oneday=datetime.timedelta(days=1) 
        yesterday=today-oneday  
        return yesterday
     
    # 输出
    print(getYesterday())

    li = ["a", "b", "mpilgrim", "z", "example"]
    print(li)
    print(li[1])
    print(li[-1])
    print(li[1:3])
    print(li[1:-1])
    print(li[0:3])
    li.append("new")
    print(li)
    li.insert(2, "new")
    print(li)
    li.extend(["two", "elements"])
    print(li)
    print(li.index("example"))
    li.remove("z")
    print(li)
    print(li.pop())

    li = ['a', 'b', 'mpilgrim']
    print(li)
    li = li + ['example', 'new']
    print(li)
    li += ['two'] 
    print(li)
    li = [1, 2] * 3
    print(li)

    params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    print(params)
    aa = ["%s=%s" % (k, v) for k, v in params.items()]
    print(aa)
    bb = ";".join(["%s=%s" % (k, v) for k, v in params.items()])
    print(bb)
    li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
    print(li)
    s = ";".join(li)
    print(s)
    print(s.split(";"))
    print(s.split(";", 1))

    li = [1, 9, 8, 4]
    print(li)
    aa = [elem*2 for elem in li]
    print(aa)
    params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
    print(params.keys())
    print(params.values())
    print(params.items())
    bb = [k for k, v in params.items()]
    print(bb)
    cc = [v for k, v in params.items()]
    print(cc)
    dd = ["%s=%s" % (k, v) for k, v in params.items()]
    print(dd)
    li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
    print(li)
    ee = [elem for elem in li if len(elem) > 1]
    print(ee)
    ff = [elem for elem in li if elem != "b"]
    print(ff)
    gg = [elem for elem in li if li.count(elem) == 1]
    print(gg)

    people={}
    for x in range(1,31):
        people[x]=1
    # print(people)
    check=0
    i=1
    j=0
    while i<=31:
        if i == 31:
            i=1
        elif j == 15:
            break
        else:
            if people[i] == 0:
                i+=1
                continue
            else:
                check+=1
                if check == 9:
                    people[i]=0
                    check = 0
                    print("{}号下船了".format(i))
                    j+=1
                else:
                    i+=1
                    continue

    import time
     
    print('按下回车开始计时,按下 Ctrl + C 停止计时。')
    while True:
        try:
            input() # 如果是 python 2.x 版本请使用 raw_input() 
            starttime = time.time()
            print('开始')
            while True:
                print('计时: ', round(time.time() - starttime, 0), '', end="
    ")
                time.sleep(1)
        except KeyboardInterrupt:
            print('结束')
            endtime = time.time()
            print('总共的时间为:', round(endtime - starttime, 2),'secs')
            break

    def sumOfSeries(n):
        sum = 0
        for i in range(1, n+1):
            sum +=i*i*i
             
        return sum
     
       
    # 调用函数
    n = 5
    print(sumOfSeries(n))

    # 定义函数,arr 为数组,n 为数组长度,可作为备用参数,这里没有用到
    def _sum(arr,n):
         
        # 使用内置的 sum 函数计算
        return(sum(arr))
     
    # 调用函数
    arr=[]
    # 数组元素
    arr = [12, 3, 4, 15]
     
    # 计算数组元素的长度
    n = len(arr)
     
    ans = _sum(arr,n)
     
    # 输出结果
    print ('数组元素之和为',ans)

    def leftRotate(arr, d, n):
        for i in range(d):
            leftRotatebyOne(arr, n)
    def leftRotatebyOne(arr, n):
        temp = arr[0]
        for i in range(n-1):
            arr[i] = arr[i+1]
        arr[n-1] = temp
             
    def printArray(arr,size):
        for i in range(size):
            print ("%d"% arr[i],end=" ")
     
    arr = [1, 2, 3, 4, 5, 6, 7]
    leftRotate(arr, 2, 7)
    printArray(arr, 7)

    def swapList(newList):
        size = len(newList)
        temp = newList[0]
        newList[0] = newList[size - 1]
        newList[size - 1] = temp
        return newList
    
    newList = [1, 2, 3]
     
    print(swapList(newList))

    def swapPositions(list, pos1, pos2):
        list[pos1], list[pos2] = list[pos2], list[pos1]
        return list
     
    List = [23, 65, 19, 90]
    pos1, pos2  = 1, 3
     
    print(swapPositions(List, pos1-1, pos2-1))

    def Reverse(lst):
        return [ele for ele in reversed(lst)]
         
    lst = [10, 11, 12, 13, 14, 15]
    print(Reverse(lst))

    def Reverse(lst):
        lst.reverse()
        return lst
         
    lst = [10, 11, 12, 13, 14, 15]
    print(Reverse(lst))

    test_list = [ 1, 6, 3, 5, 3, 4 ]
     
    print("查看 4 是否在列表中 ( 使用循环 ) : ")
     
    for i in test_list:
        if(i == 4) :
            print ("存在")
     
    print("查看 4 是否在列表中 ( 使用 in 关键字 ) : ")
    
    if (4 in test_list):
        print ("存在")

    from bisect import bisect_left  
     
    # 初始化列表
    test_list_set = [ 1, 6, 3, 5, 3, 4 ]
    test_list_bisect = [ 1, 6, 3, 5, 3, 4 ]
     
    print("查看 4 是否在列表中 ( 使用 set() + in) : ")
     
    test_list_set = set(test_list_set)
    if 4 in test_list_set :
        print ("存在")
     
    print("查看 4 是否在列表中 ( 使用 sort() + bisect_left() ) : ")
     
    test_list_bisect.sort()
    if bisect_left(test_list_bisect, 4):
        print ("存在")

    RUNOOB = [6, 0, 4, 1]
    print('清空前:', RUNOOB)  
     
    RUNOOB.clear()
    print('清空后:', RUNOOB) 

    def clone_runoob(li1):
        li_copy = li1[:]
        return li_copy
     
    li1 = [4, 8, 2, 10, 15, 18]
    li2 = clone_runoob(li1)
    print("原始列表:", li1)
    print("复制后列表:", li2)

    def clone_runoob(li1):
        li_copy = []
        li_copy.extend(li1)
        return li_copy
     
    li1 = [4, 8, 2, 10, 15, 18]
    li2 = clone_runoob(li1)
    print("原始列表:", li1)
    print("复制后列表:", li2)

    def countX(lst, x):
        count = 0
        for ele in lst:
            if (ele == x):
                count = count + 1
        return count
     
    lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
    x = 8
    print(countX(lst, x))

    def countX(lst, x):
        return lst.count(x)
     
    lst = [8, 6, 8, 10, 8, 20, 10, 8, 8]
    x = 8
    print(countX(lst, x))

    total = 0
     
    list1 = [11, 5, 17, 18, 23]  
     
    for ele in range(0, len(list1)):
        total = total + list1[ele]
     
    print("列表元素之和为: ", total)

    total = 0
    ele = 0
     
    list1 = [11, 5, 17, 18, 23]  
     
    while(ele < len(list1)):
        total = total + list1[ele]
        ele += 1
         
    print("列表元素之和为: ", total)

    list1 = [11, 5, 17, 18, 23]
    
    def sumOfList(list, size):
       if (size == 0):
         return 0
       else:
         return list[size - 1] + sumOfList(list, size - 1)
         
    total = sumOfList(list1, len(list1))
    
    print("列表元素之和为: ", total)

    def multiplyList(myList) :
        result = 1
        for x in myList:
             result = result * x  
        return result  
         
    list1 = [1, 2, 3]  
    list2 = [3, 2, 4]
    print(multiplyList(list1))
    print(multiplyList(list2))

  • 相关阅读:
    每次VS code中添加新项目格式化就会失效
    Odoo14学习笔记(14) 设置记录规则
    Odoo14学习笔记(13) 用户组权限设置
    微信小程序学习笔记(6) 使用wx.navigateTo做页面跳转
    微信小程序学习笔记(5) 使用wx:for循环显示数据
    微信小程序学习笔记(4) 第三方库request promise使用
    微信小程序学习笔记(3) 第一版小程序发布
    微信小程序学习笔记(2) 图片不显示问题总结
    微信小程序学习笔记(1) 学习开始
    Odoo14学习笔记(12) 在Tree/View中增加自增序号
  • 原文地址:https://www.cnblogs.com/tszr/p/11859216.html
Copyright © 2020-2023  润新知