十六. 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. Redis持久化AOF和RDB对比

    RDB持久化 AOF持久化 全量备份,一次保存整个数据库 增量备份,一次保存一个修改数据库的命令 保存的间隔较长 保存的间隔默认一秒 数据还原速度快 数据还原速度一般 save会阻塞,但bgsave或 ...

  2. 决策论 | 信息论 | decision theory | information theory

    参考: 模式识别与机器学习(一):概率论.决策论.信息论 Decision Theory - Principles and Approaches 英文图书 What are the best begi ...

  3. English Voice of <<Beautiful now>>

    Beautiful Now  -Zedd & Jon Bellion I see what you're wearing, there's nothing beneath it 我看见了你身着 ...

  4. OnSen UI结合AngularJs打造”美团"APP"我的”页面 --Hybrid App

    1.页面效果图: 演示地址:http://www.nxl123.cn/bokeyuan/meiTuanDemo_mine/ 2.核心代码 mine.html: <ons-page id=&quo ...

  5. linux进程管理之优先级

    进程优先级 nice ==================================================================================== Linu ...

  6. hihocoder-1415 后缀数组三·重复旋律3 两个字符串的最长公共子串

    把s1,s2拼接,求Height.相邻的Height判断左右串起点是否在两个串中,另外对Height和s1.length()-SA[i-1]取min. #include <iostream> ...

  7. node初学者笔记

    helloworld 编辑一个js文件——在该文件所属目录打开命令行cmd——输入'node -v可查看版本——输入'node  00-hellowolrd.js(你的js名字)' 或者直接在文件所属 ...

  8. Jquery常用的一些事件 keyup focus

    (1)keyup 事件能在用户每次松开按键时触发,实现即时提醒: (2)focus 事件能在元素得到焦点的时候触发,也可以实现即时提醒. (3)为了使表单填写准确,在表单提交之前,需要对表单的必须填写 ...

  9. fiddler 显示server ip

    Fiddler显示服务器ip地址列(方便查看host是否生效) 2016年08月31日 15:40:10 阅读数:5801 1.点击菜单栏rules——customize rules... 2.ctr ...

  10. verilog的移位运算符(存在不公平现象)

    从上面的例子可以看出,start在移过两位以后,用0来填补空出的位.进行移位运算时应注意移位前后变量的位数,下面举例说明. 4’b1001<<1 = 5’b10010; //左移1位后用0 ...