zoukankan      html  css  js  c++  java
  • python习题实例(上)_update18/07/03

      用以记录python学习过程中做过的小习题~ ヾ(◍°∇°◍)ノ゙

    1.生成两个列表,分别存放将100以内的偶数&奇数

    odd_number=[]
    even_number=[]
    for i in range(1,101):
        if i%2==0:
            odd_number.append(i)
        else:
            even_number.append(i)
    print 'the odd number list is:','
    ',odd_number
    print 'the even number list is:','
    ',even_number

    执行结果

    the odd number list is: 
    [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
    the even number list is: 
    [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]

    知识点

    range()

    创建一个整数列表,一般用在 for 循环中

    range(start, stop[, step])

    参数说明:

    start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);

    stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5

    step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)

    >>> a=range(1,5)
    >>> print a
    [1, 2, 3, 4]

    list.append()

    在列表末尾添加新的对象, 该方法无返回值,但是会修改原来的列表。

    list.append(obj)

    obj -- 添加到列表末尾的对象

    >>> a=[1,2,3]
    >>> a.append(4)
    >>> a
    [1, 2, 3, 4]

    ‘ ’

    换行符

    >>> print 'hello','
    ','world'
    hello 
    world

    2.生成8位密码,需包含大小写字母,数字,下划线

    import random
    
    number=str(random.randint(0,9))
    lower=str(chr(random.randint(97,122)))
    capital=str(chr(random.randint(65,90)))
    underline='_'
    
    type=[number,lower,capital,underline]
    new_type=random.choice(type)
    password=[number,lower,capital,underline]
    
    i=1
    while i <=4:
        password.append(new_type)
        i+=1
    else:
        random.shuffle(password)
    
    print ''.join(password) 

     

    执行结果

    _yyy5yyX

    _xxx7xBx

    ……

    知识点

    random模块

    获取随机数模块,使用前需导入,import random。

    常用函数:

    random.random

    返回随机生成的一个实数,它在[0,1)范围内。

    >>> random.random()
    0.005544345491154901

    random.randint

    生成一个指定范围内的整数,其中范围包含上下限

    >>> random.randint(1,10)
    4

    random.choice

    从序列中获取一个随机元素,并返回

    >>> a=[1,2,3]
    >>> random.choice(a)
    3
    >>> random.choice('hello')
    'l'

    random.shuffle

    随机排列列表中的元素,会修改列表本身。

    >>> a
    [2, 1, 3]
    >>> a=[1,2,3]
    >>> random.shuffle(a)
    >>> a
    [3, 2, 1]
    >>> random.shuffle(a)
    >>> a
    [2, 3, 1]

    join()

    将序列中的元素以指定的字符连接生成一个新的字符串

    str.join(sequence)

    sequence -- 要连接的元素序列。

    >>> str='-'
    >>> seq=['a','b','c']
    >>> print str.join(seq)
    a-b-c

      

    3.列表元素去重

    方法一

    list_a=[1,1,1,2,2]
    list_b=[]
    
    for i in list_a:
        if i in list_b:
            continue
        else:
            list_b.append(i)
    
    print list_b

    执行结果

    [1, 2]

      

    方法二

    >>> list_a=[1,1,1,2,2]
    >>> list(set(list_a))
    [1, 2]

    知识点

    set()

    创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等

    set([iterable])

    iterable -- 可迭代对象对象

    >>> x=set('hello')
    >>> y=set('good world')
    >>> x,y      # 重复的被删除
    (set(['h', 'e', 'l', 'o']), set([' ', 'd', 'g', 'l', 'o', 'r', 'w']))
    >>> x&y      # 交集
    set(['l', 'o'])
    >>> x|y      # 并集
    set([' ', 'e', 'd', 'g', 'h', 'l', 'o', 'r', 'w'])
    >>> x-y      # 差级
    set(['h', 'e'])

    4.统计一个字符串,有多少个特定字符

     统计这句话有几个字母‘a’

    方法一

    s='i am a boy'
    count=0
    for i in s:
        if i =='a':
            count+=1
    print count

    执行结果

    2

    方法二

    >>> s='i am a boy'
    >>> s.count('a')
    2

    知识点

    count()

    用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

    str.count(sub, start= 0,end=len(string)) 

    >>> s='i am a boy'
    >>> s.count('a')
    2
    
    >>> s='i am a boy'
    >>> s.count('a',3,9)
    1

    对序列也可以使用

    >>> ss=['1','a','a','3']     #列表
    >>> ss.count('a')
    2
    >>> ss=('1','a','a','3')     #元祖
    >>> ss.count('a')
    2

    统计这句话有几个单词包含字母‘a’

    s='i am a boy'
    count=0
    a_word=[]
    new_dict=s.split(' ')
    for i in new_dict:
        if 'a' in i:
            count+=1
            a_word.append(i)
    print 'count is:',count
    print 'word list is:',a_word

    运行结果

    count is: 2
    word list is: ['am', 'a']

    知识点

    split()

    通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串

    str.split(str="", num=string.count(str)).

    str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。

    num -- 分割次数。

    >>> str='hello-good-world'
    >>> print str.split('-')
    ['hello', 'good', 'world']

    5.判断一个数是不是质数

    # -*- coding: utf-8 -*- 
    import math
    number=int(raw_input('please enter a number:'))
    for i in range(2,int(math.sqrt(number)+1)):     #平方根方法
    #for i in range(2,number):
        if number % 2 != 0:
            print u'是质数'
            break
    else:
        print u'不是质数'

    运行结果

    please enter a number:89
    是质数

    知识点

    Math模块

    math.sqrt

    返回数字的平方根,使用前先导入math模块

    >>> import math
    >>> math.sqrt(6)
    2.449489742783178

    math.pow

    返回 xy(x的y次方) 的值

    math.pow( x, y )

    >>> math.pow(2,3)
    8.0

    math.ceil/floor

    向上/下取整

    >>> math.ceil(1.1)
    2.0
    >>> math.floor(1.1)
    1.0

    其他几个常见函数

    abs

    返回数值的取绝对值

    >>> abs(1)
    1
    >>> abs(-1)
    1

    round

    将数值四舍五入

    >>> round(1.1111)
    1.0
    >>> round(1.5555)
    2.0

    cmp

    比较两个数值的大小

    >>> cmp(1,1)    #相等
    0
    >>> cmp(2,1)    #大于
    1
    >>> cmp(1,2)    #小于
    -1

    max&min

    找出序列中最大/最小的数值

    >>> max([1,2,3,4])
    4
    >>> min([1,2,3,4])
    1

    6.输入一组数字,将每位数字加1后输出

    方法一
    number=str(int(raw_input('enter a number:')))
    new_number=''
    for i in number:
        i_new=int(i)+1
        new_number+=str(i_new)
    print int(new_number)
    
    方法二
    number=raw_input('enter a number:')
    list1=[]
    list2=[]
    for i in number:
        list1.append(i)
    
    for j in list1:
        list2.append(str(int(j)+1))
    print int(''.join(list2))
    
    方法三
    >>> int(''.join(map(lambda x:str(int(x)+1),'123')))
    234
    

      

    运行结果

    enter a number:123
    234
    

      

    知识点

    lambda

    lambda表达式,通常是在需要一个函数,但是又不想命名一个函数的场合下使用,也就是指匿名函数。

    创建语法:lambda parameters:express

    parameters:可选,如果提供,通常是逗号分隔的变量表达式形式,即位置参数。

    expression:不能包含分支或循环(但允许条件表达式),也不能包含return(或yield)函数。如果为元组,则应用圆括号将其包含起来。

    eg
    >>> s=lambda x:x+1     					#传入一个参数
    >>> print s(1)
    2
    
    >>> p=lambda x,y:x+y					#传入多个参数
    >>> print p(1,2)
    3
    
    >>> s=lambda x:'yes' if x==1 else 'no'			#条件表达式
    >>> s(0)
    'no'
    >>> s(1)
    'yes'
    

      

     PS:

    Lambda函数返回值是一个地址,即函数对象

    >>> lambda x:x+1

    <function <lambda> at 0x0000000002E53CF8>

      

    map()

    根据提供的函数对指定序列做映射,并返回一个新的序列

    函数语法:map(function, iterable, ...)

    function -- 函数

    iterable -- 一个或多个序列

    eg.

    >>> def x(s):
           return s+1
    >>> map(x,[1,2,3])                                               #包含一个参数
    [2, 3, 4]
    
     
    >>> map(lambda x,y:x+y,[1,2,3],[10,20,30])                       #包含两个参数
    [11, 22, 33]
    

      

    7.阶乘函数

    def factorial(x):
        result=1
        if not isinstance(x,int):
            raise TypeError('bad operand type')
        if x> 0:
            for i in range(1,x+1):
                result*=i
            return result
        elif x==0:
            return '1'
        else:
            return 'please enter a positive number'
    
    print factorial('s')        
    print factorial(3)
    print factorial(-1)
    print factorial(0)
    

       

    运行结果

    print factorial('s')  							#非整数
    raise TypeError('bad operand type')
    TypeError: bad operand type
    print factorial(3)							#正整数
    6
    print factorial(-1)							#负数
    please enter a positive number
    print factorial(0)							#0
    1
    

      

    知识点

    isinstance()

    用来判断一个对象是否是一个已知的类型,类似 type()

    isinstance() 与 type() 区别:

    type() 不会认为子类是一种父类类型,不考虑继承关系。

    isinstance() 会认为子类是一种父类类型,考虑继承关系。

    如果要判断两个类型是否相同推荐使用 isinstance()。

    语法:isinstance(object, classinfo)

    object -- 实例对象。

    classinfo -- 可以是直接或间接类名、基本类型或者由它们组成的元组。

    如果对象的类型与参数二的类型(classinfo)相同则返回 True,否则返回 False。

    eg

    >>> isinstance(1,int)
    True
    >>> isinstance(1,str)
    False
    >>> isinstance(1,(str,int,list))			# 如果是元组中的其中一个则返回True
    True
    

      

    raise()

    raise语句来引发一个异常。异常/错误对象必须有一个名字,且它们应是Error或Exception类的子类。

    eg.

    >>> def ThrowErr():
    	raise Exception('my name is error')
    >>> ThrowErr()
    Traceback (most recent call last):
      File "<pyshell#44>", line 1, in <module>
        ThrowErr()
      File "<pyshell#43>", line 2, in ThrowErr
        raise Exception('my name is error')
    Exception: my name is error
    

      

    8.定义一个函数,可以设定不定个数的形参,返回形参中的乘方和

    def powersum(power,*args):
        total=0
        for i in args:
            total+=pow(i,power)
        return total
    

      

    运行结果

    print powersum(2,3)
    9
    print powersum(2,3,4)
    25
    print powersum(2,3,4,5)
    50
    

      

    知识点

    *args 和**args都可以接受可变长度的参数个数

    *args :表示的是可变参数的元祖

    **args:表示的是可变参数的字典

    pow()

    内置pow函数

    语法:pow(x, y[, z])

    计算x的y次方,如果z在存在,则再对结果进行取模

    eg.

    >>> pow(2,3)
    8
    >>> pow(2,3,4)
    0
    >>> pow(2,3,5)
    3
    

       

    PS:

    与math.pow的区别

    pow() 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块则会把参数转换为 float。

    9.定义一个函数,使用可变参数字典,计算所有参数的key和value的长度,并返回结果

    def count_length(**args):
        result=0
        for key,value in args.items():
            result+=len(str(key))
            result+=len(str(value))
        return result
    print count_length(a='hello',b='world')
    

      

    运行结果

    12

    知识点

    dict.item()

    以列表返回可遍历的(键, 值) 元组数组。

    eg.

    >>> dict={'name':'hello','age':15}
    >>> print dict.items()
    [('age', 15), ('name', 'hello')]
    
    >>> for key,value in dict.items():
    	print key,value
    
    age 15
    name hello
    

      

     10.查询列表中元素是列表的个数

    方法一:
    a=[1,[2],[3],'a']
    j=0
    for i in a:
        if isinstance(i,list):
            j+=1
    print j
    
    运行结果:
    2
    
    方法二: >>> a=[1,[2],[3],'a'] >>> len(filter(lambda x:isinstance(x,list),a)) 2

      

    知识点

    Filter

    用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表

    语法:filter(function, iterable)

    function -- 判断函数。

    iterable -- 可迭代对象。

    #过滤小写字母,返回大写字母

    方法一
    def f(s):
        if s>='a' and s<='z':
            return
        else:
            return s
    
    print filter(f,'AABBaabb')
    
    方法二:
    >>> import string
    >>> filter(lambda x:x in string.uppercase,'AABBaabb')		# string.uppercase返回所有大写字母
    'AABB'
    
    注: Python2中filter返回一个列表,而python3中返回一个类,py 3代码如下: >>> a=[1,[2],[3],'a'] >>> len(list(filter(lambda x:isinstance(x,list),a))) 2

      

    #删除列表中等于4的元素

    方法一
    a=[1,2,4,4,4,4,5,6]
    num=a.count(4)
    for i in a:
        if i == 4:
            while num>0:
                a.remove(i)
                num-=1
    print a
    
    运行结果:
    [1, 2, 5, 6]
    
    方法二:
    >>> a=[1,2,4,4,4,4,5,6]
    >>> filter(lambda x:x!=4,a)
    [1, 2, 5, 6]
    

      

    11.按照列表的长度倒序排列

    list1=[(1,5,6),(1,2,3,4),(1,1,2,3,4,5),(1,9)]
    def l(tup):
        return len(tup)
    
    list1.sort(key=l,reverse=True)
    print list1
    

      

    知识点

    L.sort(cmp=None,key=None,reverse=False)

    key:从每个元素提起一个用于比较的关键字

    reverse:接受false或者true,表示是否逆序。True,表示逆序

    #按照列表第一个元素的大小排序

    list1=[(1,5,6),(7,2,3,4),(8,1,2,3,4,5),(2,9)]
    def L(tup):
        return tup[0]
    list1.sort(key=L)
    
    print list1
    
    运行结果:
    [(1, 5, 6), (2, 9), (7, 2, 3, 4), (8, 1, 2, 3, 4, 5)]
    

      

    12.将两个list的对应位元素合并

    方法一:
    list1=[1,2,3]
    list2=[4,5,6]
    list3=[]
    
    for i in range(len(list1)):
        for j in range(len(list2)):
            if i==j:
                tup=(list1[i],list2[j])
                list3.append(tup)
    print list3
    
    方法二:
    >>> zip([1,2,3],[4,5,6])
    [(1, 4), (2, 5), (3, 6)]
    

      

    知识点

    zip()

    用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

    注意:python 3中zip返回的是一个地址,需要用list转化一下

    >>> zip([1,2,3],[4,5,6])
    <zip object at 0x000000000290FB88>
    >>> list(zip([1,2,3],[4,5,6]))
    [(1, 4), (2, 5), (3, 6)]
    

      

    已经压缩过的列表,添加个*号,即为解压

    >>> a=[1,2,3]
    >>> b=[4,5,6]
    >>> s=zip(a,b)
    >>> zip(*s)
    [(1, 2, 3), (4, 5, 6)]
    

      

    13.生成一个0~8的二维列表

    result=[]
    num=0
    for i in range(3):
        x=[]
        for j in range(3):
            x.append(num)
            num+=1
        result.append(x)
    
    print result
    
    运行结果:
    [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

    14.二维列表转置

    方法一:
    A=[[1,2,3],
       [4,5,6],
       [7,8,9],
       [10,11,12]]
    result=[]
    
    for i in range(3):
        L=[]
        for j in range(4):
            L.append(A[j][i])
        result.append(L)
            
    
    print result
    
    
    方法二:
    >>> A=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
    >>> print [ [ j [ i ] for j in A]for i in range(3) ]


    运行结果:
    [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

      

    知识点

    推导列表

    格式:[表达式 for 变量 in 列表]   或者  [表达式 for 变量 in 列表 if 条件]

    PS:支持for if循环,但是不支持else

    >>> [x for x in range(5)]
    [0, 1, 2, 3, 4]
    >>> [x+1 for x in range(5)]
    [1, 2, 3, 4, 5]
    >>> [x+y for x in [1,2,3] for y in [4,5,6]]
    [5, 6, 7, 6, 7, 8, 7, 8, 9]
    

      

    15.交换字典key与value的位置

    d={'a':1,'b':2}
    new_d={}
    for i,j in d.items():
        new_d[j]=i
    print new_d
    

      

    上篇结束 ,撒花✿✿ヽ(°▽°)ノ✿

  • 相关阅读:
    Android基础总结(四)网络通信
    Android基础总结(三)SQLite,ListView,对话框
    am335x sd卡启动系统参数设置
    am335x 电容屏驱动添加。
    linux 下恢复后台程序的方法
    qt-5.6.0 移植之实现板子与ubuntu主机通过网络进行文件传输
    qt-5.6.0 移植之qt文件系统的建立
    qt-5.6.0 移植之tslib 配置及编译
    qt-5.6.0 移植之qt源码编译
    qt-5.6.0 移植之纯净的linux文件系统的建立
  • 原文地址:https://www.cnblogs.com/lilip/p/9231142.html
Copyright © 2011-2022 走看看