本实例要求用python编写最简短的程序,自定义一个有十个商品价格的表,实现设置价格区间和价格排序的功能
时间: 2024-05-11 12:14:18 浏览: 5
以下是一个简短的Python程序,可以自定义一个包含十个商品价格的表,并实现设置价格区间和价格排序的功能:
```python
prices = [12.5, 23.6, 7.8, 45.3, 32.9, 18.6, 9.1, 27.4, 14.7, 36.8]
# 设置价格区间
min_price = 10
max_price = 30
filtered_prices = [p for p in prices if p >= min_price and p <= max_price]
print("价格区间为 {} 到 {} 的商品价格为:{}".format(min_price, max_price, filtered_prices))
# 价格排序
sorted_prices = sorted(prices)
print("商品价格从低到高排序为:", sorted_prices)
```
输出:
```
价格区间为 10 到 30 的商品价格为:[12.5, 23.6, 18.6, 27.4, 14.7]
商品价格从低到高排序为: [7.8, 9.1, 12.5, 14.7, 18.6, 23.6, 27.4, 32.9, 36.8, 45.3]
```
该程序首先定义了一个包含十个商品价格的列表 `prices`,然后通过列表推导式实现了根据价格区间筛选商品价格的功能,并输出结果。接着使用了内置函数 `sorted()` 对商品价格进行排序,并输出结果。