Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 数学目录错误_Python_Math - Fatal编程技术网

Python 数学目录错误

Python 数学目录错误,python,math,Python,Math,我正在做一个简单的转换器,并将所有转换因子存储在目录中。它接受要从和转换到的内容,检查以确保它是可转换的,并获取需要转换的内容,然后出错并返回此错误: Traceback (most recent call last): File "python", line 20, in <module> TypeError: string indices must be integers 你知道它为什么会出错,如何修复它,或者用其他方法来避免错误吗?谢谢。行conversion=firs

我正在做一个简单的转换器,并将所有转换因子存储在目录中。它接受要从和转换到的内容,检查以确保它是可转换的,并获取需要转换的内容,然后出错并返回此错误:

Traceback (most recent call last):
   File "python", line 20, in <module>
TypeError: string indices must be integers

你知道它为什么会出错,如何修复它,或者用其他方法来避免错误吗?谢谢。

conversion=first[second]
的工作方式与您的预期不同
first
是一个字符串。它不是由该字符串命名的变量。要获取变量,您需要执行
eval(first)
,而
eval
通常是个坏主意

当您发现自己将变量名作为数据处理时,这通常意味着您组织错误。不要试图通过名称获取变量,而是将名称作为字典中的键

在这种情况下,您已经有了相应的字典,
doable
。不要让字典的值是字符串列表(其他变量的名称),而是将其他字典放入
doable

doable = { # you might want to change this variable's name
     'pint': {'cup': 2, 'quart': 0.5, 'galleon': 0.125, 'pint': 1},
     'quart': {'cup': 4, 'quart': 1, 'galleon': 0.25, 'pint': 2},
     #...
     }
问题代码现在将变成:

if second in doable[first]: # this works exactly the same as before
    conversion = doable[first][second] # this gets an extra level of indexing
    #...

firstsecond是单位名称——它们是字符串。 你在那一行要求的是

"ounce"["gram"]
这对运行时系统来说毫无意义。字符串“盎司”中没有元素编号“克”

我推测您正试图允许用户输入目录变量的名称。这是Python中功能的严重混乱。字符串值“盎司”与变量ounce无关

相反,您必须检查转换是否“可行”。然后需要从适当的目录中获取适当的转换因子


可能的解决方案:

"galleon" is a ship powered by oars.
"Gallon" is a unit of measurement.
将转换表设置为目录目录目录。您当前的每个目录都将成为此表中的主要标题:

conversion = {
    "pint": {'cup': 2, 'quart': 0.5, 'galleon': 0.125, 'pint': 1},
    "quart": {'cup': 4, 'quart': 1, 'galleon': 0.25, 'pint': 2},
    ...
    "kilogram": {'ounce': 35.274, 'gram': 1000, 'kilogram': 1, 'pound': 2.2}
现在,您可以将转换因子引用为

conversion[first][second]

拼写详细信息:

"galleon" is a ship powered by oars.
"Gallon" is a unit of measurement.

考虑读取错误消息,并考虑“<代码>第一/代码>的类型在第20行。谢谢!它现在可以工作了,这绝对是一个进步!谢谢你的帮助!谢谢你的拼写提示!请记得投你喜欢的任何一票,尤其是“接受”你最喜欢的答案。这允许堆栈溢出正确存档问题。