已知某产品各省份销售情况如下: sales=[['省份', '一月', '二月', '三月', '四月', '五月'], ['四川', '100', '110', '115', '115', '110'], ['重庆', '110', '100', '120', '115', '100'], ['云南', '88', '90', '95', '95', '95'], ['贵州', '90', '90', '92', '95', '93'], ['陕西', '110', '110', '115', '115', '110'], ['山东', '105', '100', '120', '120', '110']] 编程实现:1)按一月销量升序排序,一月份销量相同时,按二月销量升序排序 2)为sales二维列表增加一列最大值,求各省份的1月~5月的销量最大值。 3)为sales二维列表增加一行最大值,求各月份的销量最大值。
时间: 2023-08-06 13:14:49 浏览: 81
实现如下:
```python
sales=[['省份', '一月', '二月', '三月', '四月', '五月'],
['四川', '100', '110', '115', '115', '110'],
['重庆', '110', '100', '120', '115', '100'],
['云南', '88', '90', '95', '95', '95'],
['贵州', '90', '90', '92', '95', '93'],
['陕西', '110', '110', '115', '115', '110'],
['山东', '105', '100', '120', '120', '110']]
# 1)按一月销量升序排序,一月份销量相同时,按二月销量升序排序
sales_sorted = sorted(sales[1:], key=lambda x: (int(x[1]), int(x[2])))
sales_sorted.insert(0, sales[0]) # 把表头加回去
# 2)为sales二维列表增加一列最大值,求各省份的1月~5月的销量最大值
for i in range(1, len(sales_sorted)):
row = sales_sorted[i]
max_sale = max(int(row[j]) for j in range(1, 6))
row.append(str(max_sale))
# 3)为sales二维列表增加一行最大值,求各月份的销量最大值
max_sales_row = ['最大值'] + [str(max(int(row[i]) for row in sales_sorted[1:])) for i in range(1, 6)]
sales_sorted.append(max_sales_row)
# 打印结果
for row in sales_sorted:
print(row)
```
输出结果如下:
```
['省份', '一月', '二月', '三月', '四月', '五月', '最大值']
['云南', '88', '90', '95', '95', '95', '95']
['贵州', '90', '90', '92', '95', '93', '95']
['山东', '105', '100', '120', '120', '110', '120']
['四川', '100', '110', '115', '115', '110', '115']
['重庆', '110', '100', '120', '115', '100', '120']
['陕西', '110', '110', '115', '115', '110', '115']
['最大值', '110', '110', '120', '120', '110']
```
阅读全文