MST

星途 面试题库

面试题:Python在复杂数据分析场景下if语句的筛选逻辑优化

在一个大型销售数据集中,每个数据记录是一个字典,包含'product'(产品名称)、'region'(销售地区)、'quantity'(销售数量)、'price'(单价)等信息。现在要求通过if语句筛选出特定地区(例如'North')且销售总额(quantity * price)大于10000的产品销售记录,并对这些记录按照销售总额从高到低排序。请编写Python代码实现此功能,同时要考虑代码性能优化,假设数据集非常大。
43.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
sales_data = [
    {'product': 'product1','region': 'North', 'quantity': 100, 'price': 150},
    {'product': 'product2','region': 'South', 'quantity': 200, 'price': 80},
    {'product': 'product3','region': 'North', 'quantity': 150, 'price': 90},
    # 更多数据...
]

# 使用生成器表达式筛选数据,减少内存占用
filtered_data = ((record['product'], record['quantity'] * record['price'])
                 for record in sales_data
                 if record['region'] == 'North' and record['quantity'] * record['price'] > 10000)

# 对筛选后的数据按销售总额从高到低排序
sorted_data = sorted(filtered_data, key=lambda x: x[1], reverse=True)

# 输出结果
for product, total_amount in sorted_data:
    print(f"Product: {product}, Total Amount: {total_amount}")