打开APP
userphoto
未登录

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

开通VIP
13个提升码速的python小技巧
小伙伴们,是不是每次在写python的时候都苦于只会写一些笨重的代码有时不得不借助万能的搜索引擎呢?我也是!话不多说,下面为大家带来一些提升码速的小技巧吧。
1 交换值
x, y = 1, 2print(x, y) # 1 2x, y = y, xprint(x, y) # 2 1
如上可以在同一个赋值符号下赋予多个值,并且他们是同时进行的,而传统的交换一般需要借助一个tmp,如下
tmp=xx=y # y赋值给x之后x就改变了,所以需要事先存一个tmpt=tmp2 list转string
sentence_list = ["my", "name", "is", "George"]sentence_string = " ".join(sentence_list)print(sentence_string) # my name is George3 string转list
sentence_string = "my name is George"sentence_string.split()print(sentence_string)
技巧2和3都是处理文件任务中的重要操作。
4 初始化相同值的list
[0]*100 # 包含100个0的list [6.6]*45 # 包含45个6.6的list5 合并字典
x = {'a': 1, 'b': 2}y = {'b': 3, 'c': 4}z = {**x, **y}6 翻转string
name = "George"name[::-1]print(name[::-1]) # egroeG7 函数返回多个值
def get_a_string(): a = "George" b = "is" c = "cool" return a, b, csentence = get_a_string()(a, b, c) = sentence8 列表解析(List comprehension)
a = [1, 2, 3]b = [num*2 for num in a] print(b) # [2, 4, 6]9 遍历字典
项目方法
c4oA9ID6bj8523
41Mkg2010-02-01 10:37:29
uCc0d抖音创始人张一鸣
Apj3b2010.10.13 00-26-32
47z8YuO7NV1194
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} for key, value in m.items(): print('{0}: {1}'.format(key, value))
结果如下:
a: 1b: 2c: 3d: 410 遍历列表以及下标
m = ['a', 'b', 'c', 'd']for index, value in enumerate(m): print('{0}: {1}'.format(index, value))11 删去无用的字符
name = " George "name_2 = "George///"name.strip() # 删去空格符 "George"name_2.strip("/") # 删去'/' "George"12 找到列表中的众数
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]print(max(set(test), key = test.count)) # 413 字典转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
这个会在做一些标注文件的时候用到。
看到这个觉得有用的话不妨给个一键三连~>O<。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
编程小窍门:15 个提高效率的 Python 编程技巧
python 基础测试
finalseg: 基于HMM模型的python中文分词模块
18个Python脚本可加速你的编码速度
收藏!20条非常实用的Python代码实例
Python3学习笔记(二):基本数据类型
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服