网站首页 > 技术文章 正文
接上回,这篇文章我们来讲剩下的15个常用的Python代码片段
16.将给定函数应用于两个列表的每个元素后返回两个列表之间的差异
def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]
17.链式函数调用
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9
18.使用set()仅包含唯一元素这一事实来检查列表是否具有重复值。
def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False
19.合并两个词典
def merge_two_dicts(a, b):
c = a.copy() # make a copy of a
c.update(b) # modify keys and values of a with the ones from b
return c
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_two_dicts(a, b)) # {'x': 1, 'y': 3, 'z': 4}
在 Python 3.5 及以上版本中,你也可以像下面这样:
def merge_dictionaries(a, b):
return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b)) # {'x': 1, 'y': 3, 'z': 4}
20.将两个列表转换成字典
def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values)) # {'a': 2, 'b': 3, 'c': 4}
21.枚举
list = ["a", "b", "c", "d"]
for index, element in enumerate(list):
print("Value", element, "Index ", index, )
# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
# ('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3)
22.计算执行特定代码所需的时间
import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)# ('Time: ', 1.1205673217773438e-05)
23.将else子句作为try/except块的一部分,如果没有抛出异常则执行该子句。
try:
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.
24.返回列表中出现频率最高的元素
def most_frequent(list):
return max(set(list), key = list.count)
numbers = [1,2,1,2,3,2,1,4,2]
most_frequent(numbers) #2
25.检查给定字符串是否为回文
def palindrome(a):
return a == a[::-1] #a[::-1]会反序字符串
palindrome('mom') # True
26.不需要使用 if-else 条件的情况下编写一个简单的计算器
import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25
27.随机化列表中元素的顺序
from random import shuffle
foo = [1, 2, 3, 4]
shuffle(foo) #shuffle就地工作,并返回None
print(foo) # [1, 4, 3, 2] , foo = [1, 2, 3, 4]
28.展平
def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]
29.无需使用额外变量交换两个变量值
a, b = -1, 14
a, b = b, a
print(a) # 14
print(b) # -1
30.获取缺失键的默认值
d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3
以上就是所有的内容了,感谢关注!
如果有其他问题可以通过公众号【python玩转】联系作者
- 上一篇: 第一周:熟悉Python第一天:基本概念
- 下一篇: 如果你真的想学Python可以试试我的方法
猜你喜欢
- 2025-05-28 RxJs 介绍
- 2025-05-28 19个基本的JavaScript面试问题及答案(都是实用技巧)免费送
- 2025-05-28 数组双指针直接秒杀七道题目
- 2025-05-28 确定有限状态机(DFA)-Leet
- 2025-05-28 互联网公司中:程序员大厂履历意味着什么?月薪35K?
- 2025-05-28 六十六、Leetcode数组系列(中篇)
- 2025-05-28 征服LeetCode,你的刷题之路就此开始,手把手带你了解算法奥秘
- 2025-05-28 C语言干货:函数知识详解(变量的作用域,全局变量,静态变量)
- 2025-05-28 Python 从入门到精通:一个月就够了
- 2025-05-28 如果你真的想学Python可以试试我的方法
- 258℃Python短文,Python中的嵌套条件语句(六)
- 258℃python笔记:for循环嵌套。end=""的作用,图形打印
- 257℃PythonNet:实现Python与.Net代码相互调用!
- 252℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 252℃Python实现字符串小写转大写并写入文件
- 107℃原来2025是完美的平方年,一起探索六种平方的算吧
- 91℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 83℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)