需要知道12 个 Python 单行代码1
#1.列表交集
查找两个列表之间的共同元素,例如将来自不同广告系列的客户列表相交
l1 = [1, 2, 3]
l2 = [2, 3, 4]
list(set(l1) & set(l2))
list(set(l1).intersection(set(l2)))
// [2,3]
#2 reduce
聚合列表的元素,例如汇总每日销售额
from functools import reduce
import operator
numbers = [1, 2, 3, 4]
res = reduce(operator.mul, numbers, 1)
print(res)
// 24
#3 按值排序
按字典的值组织字典,这对于确定任务紧迫性等项目的优先级很有用
d = {"a": 1, "b": 2, "c": 3}
dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
//{'c': 3, 'b': 2, 'a': 1}
#4 筛选器,并返回索引
提取特定元素的指数,例如在列表中查找最高价值客户位置
lst = [1, 2, 3, 1, 2]
target = 1
[i for i in range(len(lst)) if lst[i] == target]
// [0, 3]
#5 展平列表列表
将嵌套列表转换为单个列表,非常适合简化数据结构
list_of_lists = [[1, 2], [3, 4], [5, 6]]
# using sum
flat_list1 = sum(list_of_lists, [])
# alternative with itertools
from itertools import chain
flat_list2 = list(chain.from_iterable(list_of_lists))
assert flat_list1 == flat_list2
#6 合并两个词典
合并两组数据,例如合并月度销售数据
dict1 = {"name" : "Ben"}
dict2 = {"age" : 22}
{**dict1, **dict2}
//{'name': 'Ben', 'age': 22}
#7 过滤质数
从列表中分离质数,在某些算法问题中很有用
primes = list(filter(lambda x: all(x % y != 0 for y in range(2, int(x**0.5) + 1)), range(2, 50)))
primes
//[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
#8 any 和all
检查列表中是否满足任何或所有条件,例如验证是否有任何产品缺货
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
any_greater_than_5 = any(x > 5 for x in my_list) # Returns True
all_greater_than_5 = all(x > 5 for x in my_list) # Returns False
#9 Lambda 函数
用于将公式应用于列表等操作的快速内联函数
square = lambda x: x**2
square(5)
//25
#10 排列
生成所有可能的排序,在路线规划等场景中很有用
from itertools import permutations
my_list = [1, 2, 3]
list(permutations(my_list))
// Returns [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
#11 执行代码
将字符串作为 Python 代码动态执行,方便灵活编写脚本
exec('import math\nprint(math.sqrt(16))')
// 4.0
#12 来自列表的词典
将列表转换为词典,例如创建字数统计
list_of_keys = ['one', 'two', 'three']
list_of_values = [1, 2, 3]
dict(zip(list_of_keys, list_of_values))
//{'one': 1, 'two': 2, 'three': 3}