Python是一種強大且易上手的語言,語法簡潔優雅,不像Java那麼繁瑣廢話,並且有一些特殊的函數或語法可以讓程式碼變得更加簡短精悍。
根據筆者經驗,以下介紹常用的5個Python小技巧:
my_string = "Hi Python..!"print(my_string * 2)#Hi Python..!Hi Python..!print(my_string + " I love Python" * 2)#Hi Python..! I love Python I love Python
my_string = "Hi Python..!"print(my_string[::-1])# !..nohtyP iHmy_list = [1,2,3,4,5] print(my_list[::-1])# [5, 4, 3, 2, 1]
word_list = ["awesome", "is", "this"]print(' '.join(word_list[::-1]) + '!') #this is awesome!
def stupid_func(x): return x**2 + 5
def stupid_func(x): return x**2 + 5my_list = [1, 2, 3, 4, 5] new_list = []for x in my_list: if x % 2 != 0: new_list.append(stupid_func(x)) print(new_list)#[6, 14, 30]
def stupid_func(x): return x**2 + 5my_list = [1, 2, 3, 4, 5] print([stupid_func(x) for x in my_list if x % 2 != 0])#[6, 14, 30]
for item in list: if conditional: expression
my_list = [1, 2, 3, 4, 5]print([x ** 2 + 5 for x in my_list if x % 2 != 0])#[6, 14, 30]
stupid_func = (lambda x : x ** 2 + 5) print([stupid_func(1), stupid_func(3), stupid_func(5)])#[6, 14, 30]
my_list = [2, 1, 0, -1, -2] print(sorted(my_list))#[-2, -1, 0, 1, 2]
my_list = [2, 1, 0, -1, -2] print(sorted(my_list, key = lambda x : x ** 2))#[0, -1, 1, -2, 2]
print(list(map(lambda x, y : x * y, [1, 2, 3], [4, 5, 6]))) #[4, 10, 18]
x, y = [1, 2, 3], [4, 5, 6] z = []for i in range(len(x)): z.append(x[i] * y[i])print(z) #[4, 10, 18]
x = int(input())if x >= 10:print("Horse") elif 1 < x < 10:print("Duck")else:print("Baguette")
print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette")
first_names = ["Peter", "Christian", "Klaus"] last_names = ["Jensen", "Smith", "Nistrup"]print([' '.join(x) for x in zip(first_names, last_names)]) #['Peter Jensen', 'Christian Smith', 'Klaus Nistrup']
以上是五個節約人生的Python小技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!