摘要:monthly_salaries = [2500, 3500, 4500, 5500, 6500]# Calculate new salaries using list comprehensionnew_salaries = [salary * 0.15 +
列表推导式允许使用紧凑的语法生成列表。
假设我们有一份月薪清单,想要给每位员工加薪 15%:
monthly_salaries = [2500, 3500, 4500, 5500, 6500]# Calculate new salaries using list comprehensionnew_salaries = [salary * 0.15 + salary for salary in monthly_salaries]print(new_salaries)输出:
[2875.0, 4025.0, 5175.0, 6325.0, 7475.0]还可以根据特定条件添加条件来过滤或修改元素。
请记住,如果使用 if 条件,应该将其写到 for 循环的右侧;如果使用 if else 条件,我们应该将其写入 for 循环的左侧:
# Double salaries only if they are less than 5000new_salaries = [salary * 2 if salary输出:
列表推导式对于各种任务都很方便,例如修改数据或过滤元素:
# Convert student names to lowercase if they exist in a specific liststudents = ["Alice", "Bob", "Catherine", "David"]students_no = ["Alice", "Catherine"][student.lower if student in students_no else student.upper for student in students]与列表推导式类似,字典推导式允许我们有效地创建字典。让我们探讨一下它们的基础知识:
假设我们要创建一个字典,其中范围中的每个数字都映射到其双精度:
numbers = range(0, 10)new_dict = {number: number * 3 for number in numbers}print(new_dict)输出:
{0: 0, 1: 3, 2: 6, 3: 9, 4: 12, 5: 15, 6: 18, 7: 21, 8: 24, 9: 27}我们还可以应用条件来包含或转换键值对:
# Create a dictionary with only even values from an original dictionaryoriginal_dict = {'emma': 30, 'liam': 41, 'olivia': 52, 'noah': 29}filtered_dict = {name: age for (name, age) in original_dict.items if age % 2 == 0}print(filtered_dict)输出:
让我们探索一些更实际的例子,看看推导式如何简化常见任务:
# Modify variable names in a listvariables = ['total_amount', 'speed_limit', 'alcohol_content'][variable.upper for variable in variables]# Change DataFrame column namesimport pandas as pddf = pd.DataFrame({'total_amount': [10, 20, 30], 'speed_limit': [50, 60, 70], 'alcohol_content': [5, 8, 12]})[col.upper for col in df.columns]# Prepend "FLAG_" to column names containing "INS" in a DataFrame["FLAG_" + col if "ins" in col else "NO_FLAG_" + col for col in df.columns]通过掌握 Python 推导式您将简化代码并使其更易于理解,即使对于初学者也是如此。在 Python 项目中采用推导式可以简化数据处理并提高编码效率!
来源:自由坦荡的湖泊AI一点号
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!