zoukankan      html  css  js  c++  java
  • python 常用内置函数

    内置函数

    zip(拉链)

    拉链函数(像拉链一样相互咬合)
    参数必须是可迭代的对象,可以有多个参数,返回的对象也是可迭代对象
    
    一个参数
    l = [1, 2, 3, 4, 5, 6]
    res = zip(l)
    print(type(res))
    print(list(res)) # [(1,), (2,), (3,), (4,), (5,), (6,)]
    # 返回的是一个个元组(这个只是我把它转换成了list形式的,里面包裹了元组)
    
    二个参数
    l1 = [1, 2, 3, 4, 5, 6, 7]
    l2 = 'abcdef'
    res = zip(l1,l2)
    print(res)
    print(list(res)) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]
    warnings:如果两个可迭代对象的长度不一致,以短的位置(木桶原理)
    
    
    多个个参数
    a = 'abcdef'
    b = [1,23,45,56]
    c = ('d','E','F','Z')
    res =zip(a,b,c)
    print(list(res)) # [('a', 1, 'd'), ('b', 23, 'E'), ('c', 45, 'F'), ('d', 56, 'Z')]
    
    

    map(映射)

    必须是不少于两参数,有一个必须是func,一个是可迭代数据类型
    
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    res = map(lambda x: x ** 2, l)
    print(list(res)) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    
    
    

    filter(过滤)

    不少于俩个参数,第一个必须是func,第二个是可迭代对象,一般函数最好是判断数据类型的
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    res = filter(lambda x: x % 2 == 0,l)
    print(tuple(res))
    

    max(比较大小)

    可以一次性比较多个值
    res = max(1,2,3,4,5,6)
    print(res)
    
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    res1 = max(l)
    
    dic = {'a':49, 'b':7, 'c':18, 'ee':38}
    res1 = max(dic)
    print(res1) # ee
    
    res 2 = max(dic,key=lambda x:dic[x])
    print(res2)  # a
    

    sorterd(排序)

    # 排序
    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    res = sorted(l)
    print(res)
    
    # 有函数参数的比较
    # 英文字符比较的是十进制的大小
    
    dic = {'a':3,'d':28,'e':36}
    res = sorted(dic)
    pritn(res) # ['a', 'd', 'e']
    如果是字典的话比较的是key
    
    用函数比较的是values
    dic = {'a':3,'d':28,'e':36}
    res = sorted(dic,key=lambda x: dic[x])
    print(res) # ['a', 'd', 'e']
    
    
    dic = {'a':83,'d':98,'e':36}
    res = sorted(dic,key=lambda x: dic[x])
    print(res) ['e', 'a', 'd']
    

    reversed(反转)

    l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    res = reversed(l)
    print(list(res)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    
    lis = ['a','d','e','g','z','c']
    res = reversed(lis)
    print(list(res)) # ['c', 'z', 'g', 'e', 'd', 'a']
    
  • 相关阅读:
    Vasya and Endless Credits CodeForces
    Dreamoon and Strings CodeForces
    Online Meeting CodeForces
    数塔取数 基础dp
    1001 数组中和等于K的数对 1090 3个数和为0
    1091 线段的重叠
    51nod 最小周长
    走格子 51nod
    1289 大鱼吃小鱼
    POJ 1979 Red and Black
  • 原文地址:https://www.cnblogs.com/wait59/p/13196520.html
Copyright © 2011-2022 走看看