Python列表解析式和lambda

List Comprehensions And Lambda

Posted by BlueFat on Sunday, August 14, 2022

列表解析式 [ ]

>>> print([i for i in range(10)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> print([i for i in range(10) if i%2])
[1, 3, 5, 7, 9]

>>> print([i for i in range(10) if i%2 == 1])
[1, 3, 5, 7, 9]

>>> print([i for i in range(1,10,2)])
[1, 3, 5, 7, 9]

>>> print([i for i in range(20) if i%2==0 and i%3==0])
[0, 6, 12, 18]

>>> [[x,y] for x in 'abcde' for y in range(3)]
[['a', 0], ['a', 1], ['a', 2], ['b', 0], ['b', 1], ['b', 2], ['c', 0], ['c', 1], ['c', 2], ['d', 0], ['d', 1], ['d', 2], ['e', 0], ['e', 1], ['e', 2]]
# 1.返回1-10平方的列表
>>> [i**2 for i in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 2.有一个列表lst= [1,4,9,16,2,5,10,15],生成-个新列表, 要求新列表元素是Ist相邻2项的和
lst=[1,4,9,16,2,5,10,15]
l1=[]
for i in range(len(lst)-1):
    l1.append(lst[i]+lst[i+1])
print(l1)

print([lst[i]+lst[i+1] for i in range(len(lst)-1)])

集合{ }

>>> [{x,y} for x in 'abcde' for y in range(3)]
[{0, 'a'}, {1, 'a'}, {'a', 2}, {0, 'b'}, {'b', 1}, {'b', 2}, {0, 'c'}, {1, 'c'}, {'c', 2}, {0, 'd'}, {1, 'd'}, {2, 'd'}, {0, 'e'}, {1, 'e'}, {2, 'e'}]


>>> [(i,j) for i in range(7) if i>4 for j in range(20,25) if j>23]
[(5, 24), (6, 24)]

>>> [(i,j) for i in range(7)  for j in range(20,25) if i>4 if j>23]
[(5, 24), (6, 24)]

 >>> {str(0x61+x):x**2 for x in range(1,4)}
{'98': 1, '99': 4, '100': 9}

>>> {chr(0x41+x):x+1 for x in range(1,4)}
{'B': 2, 'C': 3, 'D': 4}

>>> {(x,):[x+1] for x in range(3)}
{(0,): [1], (1,): [2], (2,): [3]}


>>> {(x%3):x+1 for x in range(10)} #去重
{0: 10, 1: 8, 2: 9}

>>> print(list(reversed('13579')))
['9', '7', '5', '3', '1']

>>> print({reversed('ababab')})
{<reversed object at 0x10685cf50>}

# { } set(iterable) list(iterable) tuple(iterable)

>>> print([reversed('ababab')])
[<reversed object at 0x10685cf50>]

>>> print(set(reversed('ababab')))
{'b', 'a'}

lambda表达式

Python中,使用Lambda表达式构建匿名函数。

lambda x: x**2 #定义
(lambda x: x ** 2) (4) # 调用
foo = lambda х,y: (х+y) **2 # 定义函数
foo(1, 2)
# 等价于
def foo(x,y):
	return+y) **2
  • 使用lambda关键字定义匿名函数,格式为lambda [参数列表]: 表达式
  • 参数列表不需要小括号。无参就不写参数
  • 冒号用来分割参数列表和表达式部分
  • 不需要使用return。表达式的值,就是匿名函数的返回值。表达式中不能出现等号
  • lambda表达式(匿名函数)只能写在一行上,也称为单行函数

匿名函数往往用在为高阶函数传参时,使用lambda表达式,往往能简化代码

#返回常量的函数
print( (lambda :0)())

#加法匿名函数,带缺省值
print((lambda x, y=3: x + y)(5))
print((lambda x,y=3: x + y)(5,6))

# keyword-only参数
print((lambda x,*,y=30: x + y)(5))
print((lambda x, *,y=30: x + y)(5,y=10))

#可变参数
print((lambda *args: (x for x in args))(*range(5)))
print((lambda *args: [x+1 for x in args])(*range(5)))
print((lambda *args: {x%2 for x in args})(*range(5)))

[x for x in (lambda *args: map(lambda x: x+1, args))(*range(5))] #高阶函数
list(map(lambda x:x+1, range(5)))

[x for x in (lambda *args: map(lambda x: (x+1,args), args))(*range(5))]

lambda defaultdict

from collections import defaultdict
d = defaultdict(lambda : list())
d['a'].extend(range(5) )
print(d)
print(dict(d))

defaultdict(<function <lambda> at 0x103c9b200>, {'a': [0, 1, 2, 3, 4]})
{'a': [0, 1, 2, 3, 4]}

lambda sorted

x=['a', 1,'b', 20, 'c', 32]
print(sorted(x, key=str))
[1, 20, 32, 'a', 'b', 'c']

#如果按照数字排序怎么做?
x=['a', 1, 'b', 20, 'c', 32]
print( sorted(x, key= lambda x: x if isinstance(x, int) else int(x, 16)))
[1, 'a', 'b', 'c', 20, 32]