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

十六. 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'xe5xb1xaf'

>>> print(b'xe5xb1xaf'.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))))

 

原文地址:https://www.cnblogs.com/ArrozZhu/p/8393718.html