十六. 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. 生成pyd文件时提示“Unable to find vcvarsall.bat”的问题

    本文内容 Unable to find vcvarsall.bat的问题描述 问题分析 总结 一.问题描述 我们在windows下通过pip安装一些外部Python 模块(比如,pycrypto)时通 ...

  2. eclipse java项目转idea java项目Invalid bound statement (not found): com.mapper 报错问题

    再pom文件中加上 <build> <resources> <resource> <directory>src/main/java</direct ...

  3. C#读取text内容并且于testbox中展现 保留换行实现方法

    直接上代码 //新建一个储存的list List<string> listLines = new List<string>(); StreamReader sr = new S ...

  4. Using the G711 standard

    Using the G711 standard Marc Sweetgall,                          28 Jul 2006    4.74 (27 votes) 1 2 ...

  5. Dropout的理解

    https://zhuanlan.zhihu.com/p/23178423 这篇知乎文章讲的比较好,在神经网络权重取平均值和减少神经元之间复杂的共适应关系两个方面分析了为什么dropout可以解决过拟 ...

  6. 【洛谷p1060】开心的金明

    (DP背包第一题,值得记录思路呀) 开心的金明[传送门] 洛谷算法标签: 01背包问题的思路分析见[总结]01背包问题 这道题显然是典型的01背包问题,首先我们显然可以由输入的第i个物体的价格v[i] ...

  7. 378. Kth Smallest Element in a Sorted Matrix(java,优先队列)

    题目: Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the ...

  8. 用curl模拟夹带cookie的http请求

    1. 首先登录所要登录的网站,发起http请求,获取cookie 2. 获取请求的真正的路径,现在的前端比如vue都是用自定义路径映射后端路径的,比如在vue中某个请求为caojiangjiang/t ...

  9. SqlSever查询某个表的列名称、说明、备注、注释,类型等

    这周整理了数据库文档,发现用导出脚本来整理表的信息注释查看不方便,因此我就想能不能SQL语句查询表的注释或者表的字段.我就我问朋友是不是可以,他给我点指导,然后自己也在网上百度,来实现自己的想法,我把 ...

  10. const typedef 和指针的问题(这里必须初始化的才初始化了,不必须的则没有初始化)

    这里很容易搞混: tyepdef double dou;//这里是dou是double的别名 #include<iostream> using namespace std; int mai ...