Python--推导式、函数、自定义函数

技术 · 2019-01-30 · 333 人浏览

列表推导式

number_list = [number for number in range(1, 7)]
print(number_list)
------------------
[1, 2, 3, 4, 5, 6]

列表推导式加条件语句

  • if

    number_list = [number
                 for number in range(1, 7)
                 if number % 2 == 0]
    print(number_list)
    ------------------
    [2, 4, 6]

  • if else

    number_list = [number**2
                 if number % 2 == 0
                else number+10
                 for number in range(1, 7)]
    print(number_list)
    -----------------------
    [11, 4, 13, 16, 15, 36]

    几个函数

  • split()

    • 将字符串进行拆分成一个一个单词
    • 无参数
    a = 'Hello world'
    b = a.split()
    print(b)
    ------------------
    ['Hello', 'world']
      • 有1个参数
    a = 'Hello,world,I,am,coming'
    b = a.split(',')
    print(b)
    ---------------------------------------
    ['Hello', 'world', 'I', 'am', 'coming']
    • 有2个参数--->第一个为标记,第二个为切割几次

      a = 'Hello,world,I,am,coming'
      b = a.split(',',2)
      print(b)
      ---------------------------------
      ['Hello', 'world', 'I,am,coming']

      names = ['William Wang',
           'Tommy Zhao',
           'Jack Chen',
           'Mary Liu']
      first_name = [name.split()[0].lower()
                for name in names]
      print(first_name)
      ------------------------------------
      ['william', 'tommy', 'jack', 'mary']

      scores_card = {'Tom': 90, 'Jimmy': 85,
                 'Kim': 40, 'William': 99,
                 'Tommy': 61}
      passed = [name
            for name, score in scores_card.items()
            if score >= 60]
      print(passed)
      ------------------------------------
      ['Tom', 'Jimmy', 'William', 'Tommy']

自定义函数

  • def 头部

    def add(num1, num2):
      result = num1 + num2
      return print(result)
    add(10, 11)
    -----------
    21
    • def----------------函数头部

      • add----------------函数名
      • (num1,num2)----函数引用参数

自定义函数默认参数

def add(num1, num2, super_num3 = 10000):
    result = (num1 + num2)*super_num3
    return print(result)
add(10, 11)
-----------
210000
  • super_num3-—如果函数调用没有对第三个参数赋值,则默认使用参数默认值10000
函数 python 列表推导式 自定义函数
Theme Jasmine by Kent Liao