Python 的内联 if 语句(也称为三元运算符)允许您在一行中编写条件表达式。让我们探索如何有效地使用它们,以及何时它们会使您的代码变得更好。
基本内联 If 语法
下面是基本模式:
# Standard if statement
if condition:
result = value1
else:
result = value2
# Same logic as an inline if
result = value1 if condition else value2
# Example with numbers
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # Output: "adult"
# Example with strings
name = "Alice"
greeting = f"Hello, {name}" if name else "Hello, stranger"
print(greeting) # Output: "Hello, Alice"
内联 if 读起来像一个英文句子:“如果条件为 True,则将结果设置为 value1,否则将其设置为 value2”
与 Functions 组合
内联 ifs 非常适合函数调用:
def get_discount(is_member, purchase_amount):
"""Calculate discount based on membership status."""
return purchase_amount * 0.15 if is_member else purchase_amount * 0.05
# Examples
print(get_discount(True, 100)) # Output: 15.0 (15% discount)
print(get_discount(False, 100)) # Output: 5.0 (5% discount)
# Multiple conditions in the function
def get_shipping(distance, is_prime):
"""Calculate shipping cost based on distance and membership."""
base_rate = 5.0 if distance <= 50 else 10.0
return 0.0 if is_prime else base_rate
# Test the shipping function
print(get_shipping(30, True)) # Output: 0.0 (Prime member)
print(get_shipping(30, False)) # Output: 5.0 (Within 50 miles)
print(get_shipping(80, False)) # Output: 10.0 (Over 50 miles)
使用 Inline If 的列表推导式
内联 ifs 在列表推导式中大放异彩:
# Filter and transform numbers in one line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
processed = [n * 2 if n % 2 == 0 else n for n in numbers]
print(processed) # Output: [1, 4, 3, 8, 5, 12, 7, 16, 9, 20]
# Process strings with conditions
names = ["Alice", "Bob", "", "Charlie", None, "David"]
cleaned_names = [name.upper() if name else "UNKNOWN" for name in names if name is not None]
print(cleaned_names) # Output: ['ALICE', 'BOB', 'UNKNOWN', 'CHARLIE', 'DAVID']
# Data processing example
data = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
grades = [f"{d['name']}: A" if d['score'] >= 90
else f"{d['name']}: B" if d['score'] >= 80
else f"{d['name']}: C"
for d in data]
print(grades) # Output: ['Alice: B', 'Bob: A', 'Charlie: C']
使用词典
内联 ifs 可以帮助创建和修改词典:
def create_user_profile(user_data):
"""Create a user profile with default values for missing data."""
return {
"name": user_data.get("name", "Anonymous"),
"age": user_data.get("age", "Not specified"),
"status": "active" if user_data.get("last_login") else "inactive",
"role": "admin" if user_data.get("is_admin", False) else "user",
"display_name": user_data.get("nickname") if user_data.get("nickname") else user_data.get("name", "Anonymous")
}
# Example usage
user1 = {
"name": "Alice",
"age": 28,
"last_login": "2024-01-15",
"is_admin": True
}
user2 = {
"name": "Bob",
"nickname": "Bobby"
}
print(create_user_profile(user1))
print(create_user_profile(user2))
实际示例:数据处理管道
以下是在数据处理管道中使用内联 ifs 的实际示例:
def process_sales_data(sales_records):
"""Process sales records and generate summary statistics."""
# Clean and transform data
processed_records = [
{
"date": record["date"],
"amount": float(record["amount"]) if isinstance(record["amount"], str) else record["amount"],
"product": record["product"].strip().lower(),
"category": record["category"].strip() if "category" in record else "uncategorized",
"status": "completed" if record.get("payment_received") else "pending"
}
for record in sales_records
if record.get("amount") and record.get("product")
]
# Calculate statistics
total_sales = sum(record["amount"] for record in processed_records)
avg_sale = total_sales / len(processed_records) if processed_records else 0
# Generate category summaries
category_totals = {}
for record in processed_records:
cat = record["category"]
category_totals[cat] = category_totals.get(cat, 0) + record["amount"]
return {
"total_sales": total_sales,
"average_sale": avg_sale,
"status": "profitable" if total_sales > 10000 else "needs_improvement",
"top_category": max(category_totals.items(), key=lambda x: x[1])[0] if category_totals else None,
"records": processed_records
}
# Example usage
sales_data = [
{"date": "2024-01-15", "amount": "1500.50", "product": "Laptop", "category": "Electronics", "payment_received": True},
{"date": "2024-01-15", "amount": 899.99, "product": "Phone", "category": "Electronics", "payment_received": True},
{"date": "2024-01-16", "amount": "75.00", "product": "Headphones", "payment_received": False},
{"date": "2024-01-16", "amount": "2500.00", "product": "TV ", "category": "Electronics", "payment_received": True}
]
result = process_sales_data(sales_data)
for key, value in result.items():
if key != "records": # Skip printing full records for brevity
print(f"{key}: {value}")
使用 Inline If 进行错误处理
内联 ifs 可以使错误处理更加简洁:
def safe_divide(a, b):
"""Safely divide two numbers with error handling."""
return a / b if b != 0 else None
def safe_get(dictionary, key, default="Not found"):
"""Safely get a value from a dictionary."""
return dictionary[key] if key in dictionary else default
def safe_process(data):
"""Process data with multiple safety checks."""
try:
return {
"value": float(data["value"]) if isinstance(data["value"], (str, int)) else None,
"status": "valid" if data.get("value") is not None else "invalid",
"message": data.get("error", "Success") if data.get("status") == "error" else "OK"
}
except Exception as e:
return {
"value": None,
"status": "error",
"message": str(e)
}
# Examples
print(safe_divide(10, 2)) # Output: 5.0
print(safe_divide(10, 0)) # Output: None
test_dict = {"name": "Alice", "age": 30}
print(safe_get(test_dict, "name")) # Output: "Alice"
print(safe_get(test_dict, "email")) # Output: "Not found"
print(safe_process({"value": "123.45"}))
print(safe_process({"value": "invalid"}))
结论
内联 if 语句在以下情况下最有用:
- 您需要一个快速、简单的条件赋值
- 您正在使用列表推导式
- 您希望提供默认值
- 您正在处理可选的数据处理
记得:
- 保持条件简单易读
- 避免嵌套过多的内联 if
- 对复杂逻辑使用常规 if 语句
- 考虑可读性而不是简洁性