新闻中心

当前位置:首页>新闻中心>新闻动态>日积月累 Python 有意思的一些小技巧

日积月累 Python 有意思的一些小技巧

发布时间:2016-09-30 点击数:6472

括号的区别

    >>> a = [1,2,3]
    >>> a
    [1, 2, 3]
    >>> type(a)
    <type 'list'>
    >>> a = (1,2,3)
    >>> a
    (1, 2, 3)
    >>> type(a)
    <type 'tuple'>

    ( ) 表示 tuple,不可变类型

    [ ] 表示 list,可变类型


列表推导式

    >>> a = [1,2,3]
    >>> a
    [1, 2, 3]
    >>> [ ea*2 for ea in a ]
    [2, 4, 6]

元组没有元组推导式


交换

    a = 12
    b = 24
    # exchange a  b
    a, b = b, a

输出序列以及倒序输出

    print range(1,10)
    print range(1,10)[::-1]
    #output:
    #[1, 2, 3, 4, 5, 6, 7, 8, 9]
    #[9, 8, 7, 6, 5, 4, 3, 2, 1]

加 r 不转义

    print "\\savc\nff"
    print r"\\savc\nff"
    #output:
    #\savc
    #ff
    #\\savc\nff


式化 对其输出 log 信息

    print 'succeed'.center(20,'=')
    print 'fail'.center(20,'=')
    # output
    # ======succeed=======
    # ========fail========

    center 表示居中的意思


单引号和双引号都可以表示字符串

    print 'hello world'
    print "hello world"

    都是输出 hello world

    这点要注意和java区分,因为java单引号表示字符char,双引号表示字符串string


pass的使用


    如果想定义一个空函数,可以这样:

    def staCorrect():
   pass

    如果把上面的pass去掉是会报错的。

在线客服
  • 销售热线
    0536-8838268
  • 电子邮箱
    micropython@turnipsmart.com