# 你的代码“balance”怎么样？找到简洁性和可读性的平衡点

Python对初学者非常友好，许多人在开始学习编程时都会选择Python。简单易上手是你接触它之后发现的第一个优点。进一步了解之后，你可能会被它的灵活性所吸引——可通过各种方式做同一功能。

### 1.列表、字典和集合推导式

>>># Create a list for subsequentoperations
>>> numbers = [1, 2, 3, 4, 5, 6]
>>>
>>># Typical way to create a list consisting of squares
>>> squares0 = []
>>>for number in numbers:
...     squares0.append(number*number)
...
>>># List comprehensions
>>> squares1 = [number*number for number in numbers]

>>># Dictionary comprehension
>>> squares_dict = {number: number*number for number in numbers}
>>> squares_dict
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
>>>
>>># Set comprehension
>>> numbers_dups = [1, 2, 3, 4, 3, 2, 1]
>>> squares_set = {number*number for number in numbers_dups}
>>> squares_set
{16, 1, 4, 9}

### 2.Lambda函数

Lambda函数是Python中的匿名函数，通常用于小规模操作。Lambda函数可以接受一到多个参数，只需一个表达式，其语法为lambda parameters:expression。

>>># Create a list of students with theirgrading information
>>> grades = [{ name :  John ,  grade : 95}, { name :  Aaron ,  grade : 92}, { name :  Jennifer ,  grade : 100}]
>>>
>>># Sort using a regular function
...     return student[ grade ]
...
[{ name :  Aaron ,  grade : 92}, { name :  John ,  grade : 95}, { name :  Jennifer ,  grade : 100}]
>>>
>>># Sort using a lambda
[{ name :  Aaron ,  grade : 92}, { name :  John ,  grade : 95}, { name :  Jennifer ,  grade : 100}]

### 3.命名元组作数据结构

>>># Use a custom class
>>>classStudent0:
...     def__init__(self, name, gender, student_id):
...         self.name = name
...         self.gender = gender
...         self.student_id = student_id
...
>>> s0 =Student0( John ,  M , 2020001)
>>>f"Name: {s0.name}; Gender: {s0.gender}; ID #: {s0.student_id}"
Name: John; Gender: M; ID #: 2020001
>>>
>>># Use the namedtuple
>>>from collections import namedtuple
>>>Student1=namedtuple("Student1", ["name", "gender", "student_id"])
>>> s1 =Student1( Jennifer ,  F , 2020002)
>>>f"Name: {s1.name}; Gender: {s1.gender}; ID #: {s1.student_id}"
Name: Jennifer; Gender: F; ID #:2020002 

### 4.使用enumerate()和zip()进行迭代

>>># Create a list of students based ontheir arrival sequence
>>> students = [ John ,  Aaron ,  Jennifer ,  Ashley ]
>>>
>>># Lengthy way
>>>for index inrange(len(students)):
...     student = students[index]
...     print(f"Arrival # {index+1}: {student}")
...
Arrival# 1: John
Arrival# 2: Aaron
Arrival# 3: Jennifer
Arrival# 4: Ashley
>>>
>>># Concise way
>>>for index, student inenumerate(students, 1):
...     print(f"Arrival # {index}: {student}")
...
Arrival# 1: John
Arrival# 2: Aaron
Arrival# 3: Jennifer
Arrival# 4: Ashley

>>># Create two lists for zip(), with oneto one match
>>> names = [ John ,  Danny ,  Jennifer ]
>>> scores = [95, 99, 100]
>>>
>>># Lengthy way
>>>for index inrange(len(names)):
...     name, score = names[index], scores[index]
...     print(f"Name: {name}; Score: {score}")
...
Name: John; Score: 95
Name: Danny; Score: 99
Name: Jennifer; Score: 100
>>>
>>># Concise way
>>>for name, score inzip(names, scores):
...     print(f"Name: {name}; Score: {score}")
...
Name: John; Score: 95
Name: Danny; Score: 99
Name: Jennifer; Score: 100

### 5.f字符串格式化

f字符串是使用字母f（或F）作为字符串文本的前缀插入的字符串文本。为了编写简洁的代码，下面两个用例首选f字符串：

· 显示变量。最基本的用法是显示一些变量的值，以便在开发过程中进行调试。如果使用传统的format（）方法，代码会偏长。

>>># Construct a list for formatting/debugging
>>> prime_numbers = [2, 3, 5, 7, 11]
>>>
>>># Show the list using format
>>>print("Prime Numbers: {}".format(prime_numbers))
PrimeNumbers: [2, 3, 5, 7, 11]
>>>
>>># Show the list using f-string
>>>print(f"Prime Numbers: {prime_numbers}")
PrimeNumbers: [2, 3, 5, 7, 11]

· 加入变量/连接字符串。f字符串不是使用+和字符串的join（）方法，而是非常直接地用于字符串连接，并且它们具有最高的可读性。在实际操作中可用于构造文件路径，如下所示：

>>># The folder and extension
>>> folder = ./usr/images
>>> ext = .jpg
>>>
>>># File name is computed from this list
>>> names = [10, 11, 12]
>>>
>>># Construct File paths
>>># Use + for concatenation
>>> paths0 = [folder + / +str(x) + ext for x in names]
>>>
>>># Use join()
>>> paths1 = [  .join([folder,  / , str(x), ext]) for x in names]
>>>
>>># Use f strings
>>> paths2 = [f"{folder}/{x}{ext}"for x in names]

【云栖号在线课堂】每天都有产品技术专家分享！

【云栖号在线课堂 社群】https://c.tb.cn/F3.Z8gvnK

+ 订阅