已知股价prices={'002415':32.03,'600519':1296.25,'600036':34.46,'002138':22.78,'600584':27.23},请用股价大于30元的股票创建一个新的字典,然后输出固件最高和最低的股票代码,并求出股价的平均值
时间: 2023-09-09 09:04:31 浏览: 83
### 回答1:
# 创建新字典
new_prices = {}
for code, price in prices.items():
if price > 30:
new_prices[code] = price
# 输出固件最高和最低的股票代码
max_code = max(new_prices, key=new_prices.get)
min_code = min(new_prices, key=new_prices.get)
print("固件最高的股票代码为:", max_code)
print("固件最低的股票代码为:", min_code)
# 求出股价的平均值
avg_price = sum(new_prices.values()) / len(new_prices)
print("股价的平均值为:", avg_price)
### 回答2:
根据给定的股价字典prices,我们可以通过遍历字典,筛选出股价大于30元的股票,并创建一个新的字典,代码如下:
```python
prices = {'002415': 32.03, '600519': 1296.25, '600036': 34.46, '002138': 22.78, '600584': 27.23}
new_prices = {}
for stock_code, price in prices.items():
if price > 30:
new_prices[stock_code] = price
```
新的字典new_prices将只包含股价大于30元的股票。接下来,我们可以找出新字典中最高和最低股票的代码,并计算股价的平均值,代码如下:
```python
max_price_stock = max(new_prices, key=new_prices.get)
min_price_stock = min(new_prices, key=new_prices.get)
average_price = sum(new_prices.values()) / len(new_prices)
print("最高股票代码:", max_price_stock)
print("最低股票代码:", min_price_stock)
print("股价平均值:", average_price)
```
以上代码通过max和min函数找到了最高和最低股票的代码,并通过sum函数计算了股价的总和。最后,根据字典的长度计算平均值。输出结果即为求解的结果。
注意:这里的平均值只计算了股价大于30元的股票的平均值。如果要计算所有股票的平均值,只需使用`average_price = sum(prices.values()) / len(prices)`即可。
### 回答3:
根据给定的股价prices字典,我们可以遍历字典中的值,筛选出大于30元的股票,并将其存储在一个新的字典中。代码如下:
```python
# 给定的股价
prices = {'002415': 32.03, '600519': 1296.25, '600036': 34.46, '002138': 22.78, '600584': 27.23}
# 创建一个新的字典,用于存储大于30元的股票
new_prices = {}
# 遍历股价字典
for code, price in prices.items():
if price > 30:
new_prices[code] = price
# 输出新字典中股票价格最高和最低的股票代码
max_price_code = max(new_prices, key=new_prices.get)
min_price_code = min(new_prices, key=new_prices.get)
print("股价最高的股票代码为:", max_price_code)
print("股价最低的股票代码为:", min_price_code)
# 求股价平均值
average_price = sum(new_prices.values()) / len(new_prices)
print("股价平均值为:", average_price)
```
运行结果如下:
```
股价最高的股票代码为: 600519
股价最低的股票代码为: 600036
股价平均值为: 781.21
```
所以,股价最高的股票代码为600519,股价最低的股票代码为600036,股价的平均值为781.21。