Python五种实用的小技巧
开始学 Python 时,如果我能掌握这些方法,那么代码看起来会更加优美。
字符串运算
列表推导式
lambda 和 map()
单行条件语句
zip()
>>> my_string = "Hi Medium..!"
>>> print(my_string * 2)
Hi Medium..!Hi Medium..!
>>> print(my_string + " I love Python" * 2)
Hi Medium..! I love Python I love Python
>>> print(my_string[::-1])
!..muideM 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!
>>> 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]
>>> 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
>>> print([x ** 2 + 5 for x in my_list if x % 2 != ])
[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, , -1, -2]
>>> print(sorted(my_list))
[-2, -1, , 1, 2]
>>> print(sorted(my_list, key = lambda x : x ** 2))
[, -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']
相关文章