5个节约生命的python小技巧
1. 字符串操作
+
拼接字符串-
*
重复字符串
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 iH
my_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!
2. 列表推导
def stupid_func(x):
return x**2 + 5
def stupid_func(x):
return x**2 + 5
my_list = [1, 2, 3, 4, 5]
new_list = []
for x in my_list:
if x % 2 != :
new_list.append(stupid_func(x))
print(new_list)
#[6, 14, 30]
def stupid_func(x):
return x**2 + 5
my_list = [1, 2, 3, 4, 5]
print([stupid_func(x) for x in my_list if x % 2 != ])
#[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]
3. Lambda
& Map
函数
Lambda
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]
Map函数
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]
4. if-else
单行表达
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")
5. zip()
函数
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']
小节
相关文章