打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
编程小窍门:15 个提高效率的 Python 编程技巧

作者:George Seif

英文原文:https://medium.com/@george.seif94/15-python-tips-and-tricks-so-you-dont-have-to-look-them-up-on-stack-overflow-90cec02705ae

1. 交换值
x, y = 1, 2print(x, y)x, y = y, xprint(x, y)
2. 字符串列表合并为一个字符串
sentence_list = ['my', 'name', 'is', 'George']sentence_string = ' '.join(sentence_list)print(sentence_string)
3. 将字符串拆分为子字符串列表
sentence_string = 'my name is George'sentence_string.split()print(sentence_string)
4. 通过数字填充初始化列表
[0]*1000 # List of 1000 zeros [8.2]*1000 # List of 1000 8.2's
5. 字典合并
x = {'a': 1, 'b': 2}y = {'b': 3, 'c': 4}z = {**x, **y}
6. 反转字符串
name = 'George'name[::-1]
7. 从函数返回多个值
def get_a_string(): a = 'George' b = 'is' c = 'cool' return a, b, csentence = get_a_string()(a, b, c) = sentence
8. 列表解析式
a = [1, 2, 3]b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2
9. 遍历字典
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value))
10. 同时遍历列表的索引和值
m = ['a', 'b', 'c', 'd']for index, value in enumerate(m):  print('{0}: {1}'.format(index, value))
11. 初始化空容器
a_list = list()a_dict = dict()a_map = map()a_set = set()
12. 删除字符串两端的无用字符
name = '  George 'name_2 = 'George///'name.strip() # prints 'George'name_2.strip('/') # prints 'George'
13. 列表中出现最多的元素
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]print(max(set(test), key = test.count))
14. 检查对象的内存使用情况
import sysx = 1print(sys.getsizeof(x))
15. 将 dict 转换为 XML
from xml.etree.ElementTree import Elementdef dict_to_xml(tag, d): ''' Turn a simple dict of key/value pairs into XML ''' elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) elem.append(child) return elem
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
13个提升码速的python小技巧
Python开发的10个小贴士 – 码农网
Python学习教程:Day12-使用正则表达式
Python 字符串处理备忘单
Python基础知识点总结
Python入门之一
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服