每次写Python都会忘记该怎么写,最后只能去Stack Overflow查?我也一样。时间一长,这让人厌倦。
这15个Python技巧和窍门,可以帮你提高效率。
x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)
sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)
print(sentence_string)
sentence_string = "my name is George"
sentence_string.split()
print(sentence_string)
[0]*1000 # List of 1000 zeros
[8.2]*1000 # List of 1000 8.2's
x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}
name = "George"
name[::-1]
def get_a_string():
a = "George"
b = "is"
c = "cool"
return a, b, c
sentence = get_a_string()
(a, b, c) = sentence
a = [1, 2, 3]
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2
m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in m.items():
print('{0}: {1}'.format(key, value))
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()
name = " George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
import sys
x = 1
print(sys.getsizeof(x))
from xml.etree.ElementTree import Element
def 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
英文原文:
15 Python tips and tricks, so you don’t have to look them up on Stack Overflow
领取专属 10元无门槛券
私享最新 技术干货