十六. Python基础(16)--内置函数-2

1 ● 内置函数format()

Convert a value to a "formatted" representation.

print(format('test', '<7')) # 如果第二个参数的数值小于len(参数1), 那么输出结果不变

print(format('test', '>7'))

print(format('test', '^7'))


注意区别于字符串的函数format()

"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序

#'hello world'

 

"{0} {1}".format("hello", "world") # 设置指定位置

#'hello world'

 

"{1} {0} {1}".format("hello", "world") # 设置指定位置, 花括号内的数字必须从0开始, 因此, 下面的写法会导致报错

#'world hello world'

 

# "{1} {0} {1}".format("hello", "world")

 

2 ● 内置函数sum, max&min

# sum只接收可迭代对象,

print(sum([1,3])) # 4

# print(sum(1,3)) # 警告:'int' object is not iterable

# max,min可接收可迭代对象,也可接受散列的值

print(max([1,3])) # 3

print(max(1,3)) # 3

 

3 ● 内置函数slice()

l = [1,2,3,4,5]

my_slice = slice(1,5,2) # Return a slice object

print(l[my_slice]) # [2, 4], 注意用方括号, 而不是圆括号

print(l)    # [1, 2, 3, 4, 5],不改变原来的列表

比较一般的切片操作:

l = [1,2,3,4,5]

l2 = l[3:]     #相当于浅拷贝

print(l2) # [4, 5]

l2.append(123) # 改变原来的列表

print(l2)

 

4 ● 内置函数repr()

print('123') # 123

print(repr('123')) # '123' # Return the canonical string representation of the object.

 

5 ● 内置函数all()和any()

print(all(['', 1, True, [1,2]])) # False,相当于用逻辑与(and)判断

print(any(['', 1, True, [1,2]])) # True, 相当于用逻辑或(or)判断

 

6 ● 内置函数ord()

>>> print(ord('屯')) # 转成Unicode统一字名的十进制形式

23663

>>> print(chr(23663))

>>> int('5c6f', 16) # 十六进制转十进制

23663

>>> print(chr(int('5c6f', 16)))

>>> hex(23663)

'0x5c6f'

>>> oct(23663)

'0o56157'

>>> bin(23663)

'0b101110001101111'

 

>>> print('屯'.encode('utf-8'))

b'\xe5\xb1\xaf'

>>> print(b'\xe5\xb1\xaf'.decode('utf-8')) # b 不能不写!

 

7 ● 集合操作

>>> a = {1,2,3}

>>> b = {3,4,6}

>>> a|b

{1, 2, 3, 4, 6} # 并集

>>> a|b

{1, 2, 3, 4, 6}

>>> a&b # 交集

{3}

>>> a-b # 差集

{1, 2}

>>> a^b # 对称差集(把两和集合都存在的元素删除)

{1, 2, 4, 6}

 

8 ● 内置函数sort()

l = [6,3,1,9,2]

l1 = sorted(l)

print(l1)

print(l) # 不改变原来的列表

print(l.sort()) # 列表类型的方法sort()

print(l) # 改变原来的列表

'''

[1, 2, 3, 6, 9]

[6, 3, 1, 9, 2]

None

[1, 2, 3, 6, 9]

'''


集合可变, 无序(因此不能用reversed()倒序).

 

9 ● 比较字符串和列表

字符串和列表都是都是可迭代对象. 比较两个字符串或列表时, 先比较两个对象的第0个元素,大小关系即为对象的大小关系,如果相等则继续比较后续元素。

>>> a = [1,2,3]

>>> b = [3,5,6]

>>> a<b

True

>>> a>b

False

>>> s1 = 'abc'

>>> s2 = 'acb'

>>> s1>s2

False

>>> s1<s2

True

>>>

 

10 ● 匿名函数/lambda表达式


一句话的python语句:

① 三元运算

② 各种推导式, 生成器表达式

③ lambda表达式(匿名函数)

# 案例1:

add = lambda x, y : x + y

print(add(1,2)) # 3

# 案例2:

my_max = lambda x, y : x if x > y else y

print(my_max(1,2)) # 2

# lambda函数其实可以有名字

# lambda后面的参数不能加括号

 

# 注意下面两种调用匿名函数的方式

print((lambda x, y : x + y)(1,2)) # 3

print((lambda x, y : x if x > y else y)(1,2)) # 2

 

11 ● 面试综合题目1

def multipliers():

    return [lambda x:i*x for i in range(4)]

print([m(2) for m in multipliers()]) # [6, 6, 6, 6]

 

# 相当于

def multipliers():

    new_l = []

    for i in range(4):

        def func(x):

            return x*i # 这一句直到程序到m(2)时才执行

        new_l.append(func)

    return new_l # new_l写成new_l.__iter__(), 结果也一样

# 程序直到new_l填充了四个func之后, 才开始执行m(2), 这时也才开始执行x*i, 但此时i已经时3了.

print([m(2) for m in multipliers()]) # [6, 6, 6, 6]

 

##########################################

def multipliers():

    return (lambda x:i*x for i in range(4))

print([m(2) for m in multipliers()]) # [0, 2, 4, 6]

 

# 相当于

def multipliers():

    new_l = []

    for i in range(4):

        def func(x):

            return x * i # 这一句直到程序到m(2)时才执行

        yield func

# 程序没返回一个func, 就执行m(2), 也就开始执行x*i, 但此时i已经时3了.

print([m(2) for m in multipliers()]) # [0, 2, 4, 6]

 

12 ● 面试综合题目2

现有两个元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]

# 解法1

t1 = (('a'),('b'))

t2 = (('c'),('d'))

test = lambda t1, t2 : [{i:j} for i,j in zip(t1, t2)]

print(test(t1, t2))

# 或者是:

print((lambda t1,t2: [{i:j} for i,j in zip(t1, t2)])(t1, t2))

# 解法2:

print(list(map(lambda t:{t[0]:t[1]},zip(t1, t2))))

 

十六. Python基础(16)--内置函数-2的更多相关文章

  1. 十五. Python基础(15)--内置函数-1

    十五. Python基础(15)--内置函数-1 1 ● eval(), exec(), compile() 执行字符串数据类型的python代码 检测#import os 'import' in c ...

  2. python基础(16):内置函数(二)

    1. lamda匿名函数 为了解决⼀些简单的需求⽽设计的⼀句话函数 # 计算n的n次⽅ def func(n): return n**n print(func(10)) f = lambda n: n ...

  3. 第六篇:python基础_6 内置函数与常用模块(一)

    本篇内容 内置函数 匿名函数 re模块 time模块 random模块 os模块 sys模块 json与pickle模块 shelve模块 一. 内置函数 1.定义 内置函数又被称为工厂函数. 2.常 ...

  4. python基础(内置函数+文件操作+lambda)

    一.内置函数 注:查看详细猛击这里 常用内置函数代码说明: # abs绝对值 # i = abs(-123) # print(i) #返回123,绝对值 # #all,循环参数,如果每个元素为真,那么 ...

  5. python基础(15):内置函数(一)

    1. 内置函数 什么是内置函数? 就是python给你提供的,拿来直接⽤的函数,比如print,input等等,截⽌到python版本3.6.2 python⼀共提供了68个内置函数.他们就是pyth ...

  6. Python基础:内置函数

    本文基于Python 3.6.5的标准库文档编写,罗列了英文文档中介绍的所有内建函数,并对其用法进行了简要介绍. 下图来自Python官网:展示了所有的内置函数,共计68个(14*4+12),大家可以 ...

  7. Python基础编程 内置函数

    内置函数 内置函数(一定记住并且精通) print()屏幕输出 int():pass str():pass bool():pass set(): pass list() 将一个可迭代对象转换成列表 t ...

  8. 学习PYTHON之路, DAY 4 - PYTHON 基础 4 (内置函数)

    注:查看详细请看https://docs.python.org/3/library/functions.html#next 一 all(), any() False: 0, Noe, '', [], ...

  9. Python基础_内置函数

        Built-in Functions     abs() delattr() hash() memoryview() set() all() dict() help() min() setat ...

随机推荐

  1. HTML第十四章总结 HTML forms

    第十四章主要讲了 html forms,通过 forms,我们可以得到 customers' feedback,使得网页能够 interactive,本章的内容分为三个部分: forms 的 elem ...

  2. p1457 The Castle

    原图找最大的房间及房间数很容易.然后从左下到右上找拆的位置.拆掉再bfs一次找面积. #include <iostream> #include <cstdio> #includ ...

  3. Python全栈开发,Day2(in,while else,格式化输出,逻辑运算符,int与bool转换,编码)

    一.in的使用 in 操作符用于判断关键字是否存在于变量中 ? 1 2 a = '男孩wusir' print('男孩' in a) 执行输出: True in是整体匹配,不会拆分匹配. ? 1 2 ...

  4. 无线网络覆盖-java中,用Math.sqrt()时,必须要注意小数问题

    时间限制:3000 ms  |  内存限制:65535 KB 难度:3 描述 我们的乐乐同学对于网络可算得上是情有独钟,他有一个计划,那就是用无线网覆盖郑州大学. 现在学校给了他一个机会,因此他要购买 ...

  5. ubuntu opencv

    sudo apt-get updatesudo apt-get upgrade sudo apt-get install build-essential libgtk2.0-dev libjpeg-d ...

  6. php 路途一点启示

    wo:  面试了很多说后台不适合女孩,我不相信,而且我还很笨 he:不是立马就能让别人认可你,其中过程要经历很多得,有时候也要换个方式的'' wo: 我只是想用学的知识得到实践 he:那学习的过程不是 ...

  7. string用scanf读入printf输出(节省时间)

    #include <iostream> #include <stdio.h> #include <string.h> using namespace std; in ...

  8. CentOS7.3将网卡命名方式设置为传统方式

    CentOS7.3将网卡命名方式设置为传统方式 生产环境可能拥有不同系列的操作系统,比如,既有CentOS6系列,也有CentOS7系列的系统,而CentOS6和CentOS7在网卡命名方面有着较大区 ...

  9. 20165309 技能学习经验与C语言

    技能学习经验与C语言 技能学习经验 你有什么技能比大多人(超过90%以上)更好?针对这个技能的获取你有什么成功的经验?与老师博客中的学习经验有什么共通之处? 从小到大,或是出于兴趣.或是出于父母的要求 ...

  10. shiro中SSL

    对于SSL的支持,Shiro只是判断当前url是否需要SSL登录,如果需要自动重定向到https进行访问. 首先生成数字证书,生成证书到D:\localhost.keystore 使用JDK的keyt ...