15条常用Python小技巧

2019年08月11日 由 sunlei 发表 542083 0


 

你是不是也和我一样厌倦了每次在Stack Overflow上搜索时忘记如何在Python中执行某些操作?如果你的答案是“yes”,你非常幸运,这篇文章就是为你量身定制的!

这里有15个python提示和技巧可以帮助您更快地编写代码!

1、交换值


x, y = 1, 2
print(x, y)
x, y = y, x
print(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, c
sentence = 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 sys
x = 1
print(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

 

总结:


Python的小技巧还有很多,上面只是介绍了其中的一部分,入门容易精通难!在进阶的路上没有捷径,就是不断总结,不断记笔记!尤其是好的用法,就像写作文一样,好的名言警句要多背诵一些,写作的时候,肚子里的墨水多了才能才思泉涌,写出更多的好代码。

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

 
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消