Python如何将字符串“p”从列表转换为变量值p

2024-10-02 14:23:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量名列表检查.getargspec(函数).args。每个列表项都是一个变量名的字符串。我需要从函数内部使用这些字符串名称,以便检查参数变量的值是否为字符串。在

这就是我的工作

@staticmethod
def boyleslaw(p, V, k):
    """pV = k
    p=pressure Pa, V=volume m^3, k=constant
    substitute letter to solve for that value
    return x"""

    #sv = countvar(gasses.boyleslaw)
    sv = 0
    if p == 'p': sv += 1
    if V == 'V': sv += 1
    if k == 'k': sv += 1
    if sv > 1:
        raise ValueError('Too Many Variables')

    if p == 'p' and sv == 1:
        x = k/V
        return x
    elif V == 'V' and sv == 1:
        x = k/p
        return x
    elif k == 'k' and sv == 1:
        x = p*V
        return x

@staticmethod
def charleslaw(V, T, k):
    """V/T = k
    V=volume m^3, T=temperature K, k=constant
    substitute letter for value to solve for
    return x"""
    #sv = countvar(gasses.charleslaw)
    sv = 0
    if V == 'V': sv += 1
    if T == 'T': sv += 1
    if k == 'k': sv += 1
    if sv > 1:
        raise ValueError('Too Many Variables')

    if V == 'V' and sv == 1:
        x = k*T
        return x
    elif T == 'T' and  sv == 1:
        x = V*k
        return x
    elif k == 'k' and sv == 1:
        x = V/T
        return x

我想结束这个过程

^{pr2}$

在它自己的count variables函数中对参数进行计数,并检查每个参数值是否为字符串。到目前为止我要做的…然后墙+头。。。在

@staticmethod
def countvar(module):
    """Count number of Variables in args"""
    vc = 0
    alist = inspect.getargspec(module)
    for i in alist.args:
        if isinstance(i, str) == True:
            vc += 1
    return vc

无论函数的值是多少,它都返回3,因为列表.args是一个字符串。我只想在每个变量的值都是字符串的情况下递增计数器,如果有多个变量,则会引发ValueError。如何将字符串“p”转换为变量p。。。在

编辑:澄清

boyleslaw(6886019.02, 1, k) #Solve for k

inspect.getargspec(boyleslaw).args 返回['p', 'V', 'k']

我要一份清单[6886019.02, 1, 'k']

alist[0]= 返回'p'\string name

我需要return p变量值

如果值p是一个字符串(如果在调用时选择了一个变量来求解),则递增计数器用于错误处理

boyleslaw(6886019.02, 1, k)不引发错误

boyleslaw(6886019.02, V, k)raise ValueError('Too Many Variables')


Tags: and函数字符串列表forreturnifargs
3条回答

以下是另一种解决方案:

def boyleslaw(p=None, V=None, k=None):
    """Given two of the values p, V or k this method
    returns the third according to Boyle's Law."""
    assert (p is None) + (V is None) + (k is None) == 1, \
        "exactly 2 of p, V, k must be given"
    if p is None:
        return 1.0 * k / V
    elif V is None:
        return 1.0 * k / p
    elif k is None:
        return 1.0 * p * V

假设这三个量的第一个函数。然后返回第三个数量。所以你不必明确告诉这个函数要解哪个量,因为从给定的量来看,这是显而易见的。在

^{pr2}$

使用位置参数定义函数时,每个参数都将成为必需的:

>>> def foo(a, b, c):
...     pass
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 3 arguments (0 given)

因此,不需要检查是否传递了每个参数,因为Python将为您处理这些问题。在

第二部分,你不清楚你想要什么。首先,检查变量的名称是否与传递的值if V == 'V'匹配,然后对其应用一个公式,该公式不会按您的想法操作,因为不能将两个字符串相乘。在

^{pr2}$

所以我认为你真正想要的是尝试用数字进行计算,如果失败了,就提出一个适当的错误。在

为此,你可以试试这个:

try:
   V = int(V)
except ValueError:
   return "Sorry, V must be a number not %s" % V

为期望的每个参数添加此检查。这将确保你只有数字,然后你的数学计算将工作。在

如果您知道传入的值之一必须是浮点值(即,使用小数点);然后使用float()转换它,否则您将得到另一个惊喜:

>>> int('12.4')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.4'
>>> float('12.4')
12.4

编辑:

所以在你澄清之后,我想你想要的是:

def boyleslaw(variables,solvefor='k'):
    # Normalize stuff
    variables_passed = {k.lower():v for k,v in variables.iteritems()}
    solve_for = k.lower()

    if not len(variables) or len(variables) == 1:
        return "Sorry, you didn't pass enough variables"

    if solve_for in variables_passed:
        return "Can't solve for %s as it was passed in" % solvefor

此方法将字典作为变量;默认情况下,它为k求解。你可以这样称呼它:

d = {'V': 12, 't': 45}
boyleslaw(d) # default, solve for k

d = {'t': 45, 'k': 67}
boyleslaw(d,'V') # solve for V

d = {'t':1}
boyeslaw(d) # results in error "Didn't pass enough variables"

d = {'t': 45, 'k': 67}
boyleslaw(d) # results in error "Can't solve for k because k was passed in"    

我想您要查找的函数是exec语句。您可以执行类似exec("p='a string'")的操作。现在您应该能够调用p并期望'a string'

相关问题 更多 >