numpy 如何使用一个字典作为另一个字典键值的变量

rhfm7lfc  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(95)

所以我在为我的Python期末考试写一个伪的基于供需的价格板,我有一个问题,就是使用一个字典来影响另一个字典的值。首先,我有一本字典,里面有各种金属的基本成本。

metalDict = {
  'Iron Ingot': 1,
  'Copper Ingot':10,
  'Tin Ingot':30,
  'Silver Ingot':100,
  'Gold Ingot':1000,
  'Mithral Ingot':5000}

字符串
然后我有一个二级字典,它将根据各种后台计算显示所有信息,并从metalDict导入批发成本。这就是我的代码目前的样子:

outputDict = {
  "metals" : ['Iron Ingots', 'Copper Ingots', 'Tin Ingots', 'Silver Ingots', 'Gold Ingots', 'mithral Ingots'],
  "wholesale" : [metalDict['Iron Ingot'], metalDict['Copper Ingot'],metalDict['Tin Ingot'],metalDict['Silver Ingot'], metalDict['Gold Ingot'], metalDict['Mithral Ingot']],
  'city 1' : [1,2,3,4,5,6],
  'city 2' : [1,2,3,4,5,6],
  'city 3' : [1,2,3,4,5,6],
  'city 4' : [1,2,3,4,5,6],
  'city 5' : [1,2,3,4,5,6]}


我想使用metalDict基本成本(根据我编写的一个非常基本的生产算法而变化)来更新城市1 - 5的成本。这可能是不可能的,或者我可能需要用另一种方式来解决这个问题(也许为每个城市创建一个字典?);我不确定,因为我对Python相当陌生。
此外,我使用Numpy和Pandas作为输出,所以也许它们有我还不知道的功能。
我所做的是尝试通过for循环迭代值更改,但我得到了一个关键错误'city 1'(我已经删除了我的需求代码,以便强制更改发生,而不管我的'city 1'需要)。

city1Needs = np.random.randint (2, size=100)
city1Demand = 40
if city1Demand <= 40:
  for key, value in outputDict.items():
    if key == 'city 1':
      Outputdict['city 1'] = (metalDict[key]/2) + metalDict[key]


我期望发生的是它获取'city 1'的每个行索引和对应于metalDict行中每个值的数学。所以我的表看起来像这样(我不知道如何在编辑器中展开表,所以这只是两行和两列,而不是整个表):
| 第一城| City one |
| --| ------------ |
| 一、五| 1.5 |
| 十五个| 15 |

jgzswidk

jgzswidk1#

我想鼓励你考虑其他方法来组织这些数据。你不清楚你想要的最终产品是什么,但看看我在这里做了什么。通过将金属列表和城市列表分开,它可以让我一次处理一列数据,或者一次处理一行数据,而不是关注单个数字。

metals = ['Iron Ingot', 'Copper Ingot', 'Tin Ingot', 'Silver Ingot', 'Gold Ingot', 'Mithral Ingot']

cities = ['city 1','city 2','city 3','city 4','city 5']

wholesale = {
  'Iron Ingot': 1,
  'Copper Ingot':10,
  'Tin Ingot':30,
  'Silver Ingot':100,
  'Gold Ingot':1000,
  'Mithral Ingot':5000}

outputDict = {}

for city in cities:
    outputDict[city] = []
    for metal in metals:
        outputDict[city].append( wholesale[metal] * 1.5 )

from pprint import pprint
pprint(outputDict)

字符串
输出量:

{'city 1': [1.5, 15.0, 45.0, 150.0, 1500.0, 7500.0],
 'city 2': [1.5, 15.0, 45.0, 150.0, 1500.0, 7500.0],
 'city 3': [1.5, 15.0, 45.0, 150.0, 1500.0, 7500.0],
 'city 4': [1.5, 15.0, 45.0, 150.0, 1500.0, 7500.0],
 'city 5': [1.5, 15.0, 45.0, 150.0, 1500.0, 7500.0]}

相关问题