众所周知,对比其他编程语言,Python更加简洁优雅、语法清晰,可以实现庞大的功能,那么Python开发如何简化代码呢?我们一起来看看方法吧。
1. 列表推导式
对于一组列表,如果想让其所有元素翻倍,很多人都会采用以往比较经典的写法,其实Python中有更精简的办法,实例如下:
以往做法:
num = [1, 3, 5, 7, 9]
for i in range(len(num)):
num[i] = num[i] * 3
Python简化写法:
num = [1, 3, 5, 7, 9]
bag = [elem * 3 for elem in num]
2. 遍历列表
传统遍历列表是用函数表示列表的长度进行循环遍历,Python3可以省略这一步,更加简洁!
以往做法:
num = [1, 3, 5, 7, 9]
for i in range(len(num)):
print(num[i])
Python简化写法:
num = [1, 3, 5, 7, 9]
for i in num:
print(i)
3. 元素互换
对于元素互换,传统做法需要设定一个中间变量,进行数值的承接,Python元素互换变得简单了很多。
以往做法:
a = 3
b = 4
c = a
a = b
b = c
Python简化写法:
a = 3
b = 4
a,b = b,a
4. 初始化列表
Python也有简洁的初始化列表表示方法,具体简洁程度,举个例子感受一下吧,以下是要一个是8个整数1的列表
以往做法:
bag = []
for _ in range(8):
bag.append(1)
Python简化写法:
bag = [1] * 8
5. 构造字符串
经常打印字符串,需要用到构造函数,传统写法需要很多连接符和参数比较复杂,Python用法就简洁很多,以下是相关实例:
以往做法:
name = “oldboy”
age = “30”
born_in = “beijing”
str = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "."
print(str)
Python简化写法:
name = “oldboy”
age = “30”
born_in = “beijing”
str = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)
print(str)
6.返回tuples元组
Python允许一个函数中返回多个元素,以下是解包元组实例:
以往做法:
def binary():
return 0, 1
result = binary()
zero = result[0]
one = result[1]
Python简化写法:
def binary():
return 0, 1
zero, one = binary()