# 15条常用Python小技巧

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}

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))

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

END

1848 篇文章92 人订阅

0 条评论