python背诵技巧_15条常用Python小技巧
你是不是也和我一樣厭倦了每次在Stack Overflow上搜索時(shí)忘記如何在Python中執(zhí)行某些操作?如果你的答案是“yes”,你非常幸運(yùn),這篇文章就是為你量身定制的!
這里有15個(gè)python提示和技巧可以幫助您更快地編寫代碼!
1、交換值
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
2、將字符串列表合并為一個(gè)字符串列表
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、初始化一個(gè)包含數(shù)字的列表
[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、扭轉(zhuǎn)一個(gè)字符串
name = "George"
name[::-1]
7、從函數(shù)返回多個(gè)值
def get_a_string():
a = "George"
b = "is"
c = "cool"
return a, b, c
sentence = get_a_string()
(a, b, c) = sentence
8、列表推導(dǎo)
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、在獲取索引時(shí)迭代列表值
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、檢查對(duì)象的內(nèi)存使用情況
import sys
x = 1
print(sys.getsizeof(x))
15、將dict轉(zhuǎn)換為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
總結(jié):
Python的小技巧還有很多,上面只是介紹了其中的一部分,入門容易精通難!在進(jìn)階的路上沒有捷徑,就是不斷總結(jié),不斷記筆記!尤其是好的用法,就像寫作文一樣,好的名言警句要多背誦一些,寫作的時(shí)候,肚子里的墨水多了才能才思泉涌,寫出更多的好代碼。
原文鏈接:https://medium.com/@george.seif94/15-python-tips-and-tricks-so-you-dont-have-to-look-them-up-on-stack-overflow-90cec02705ae
總結(jié)
以上是生活随笔為你收集整理的python背诵技巧_15条常用Python小技巧的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信息学奥赛一本通_长乐一中老师演绎“奥赛
- 下一篇: mobsdk线上崩溃事故报告_重大事故!