Python中变量内的变量(3) [英] Variable within a Variable in Python (3)

查看:26
本文介绍了Python中变量内的变量(3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脑子可能是在错误的地方,但我想把一个变量放在一个变量中.

My head is probably in the wrong place with this, but I want to put a variable within a variable.

我编写此脚本的目标是将客户端软件的当前版本与供应商提供的当前软件版本进行比较.在这个阶段,我只想打印出可用的东西.

My goal for this script is to compare current versions of clients software with current software versions that are available from the vendor. At this stage I just want to print out what's available.

我有一些 def 设置:

I have some def's setup with:

def v80(program_1 = '80.24', program_2 = '80.5', program_3 = '80.16'):
    pass
def v81(program_1 = '81.16', program_2 = '81.7', program_3 = '81.14'):
    pass
def v82(program_1 = '82.15', program_2 = '82.4', program_3 = '82.9'):
    pass
def v83(program_1 = '83.01', program_2 = '83.0', program_3 = '83.1'):
    pass

然后我从文本文件中读取所有客户端版本并进行比较.

I'm then reading all of the clients versions from a text file and doing comparisons.

我生成的变量之一是program_main",目前我正在做类似的事情:

One of the vars I'm generating is "program_main", currently I'm doing something like:

If program_main == "83":
    if program_1:
        if v83['program_1'] > float(program_1):
            print ("Update available", program_1, "-->", v83[program_1])
    if program_2:
        if v83['program_2'] > float(program_2):
            print ("Update available", program_2, "-->", v83[program_2])
if program_main == "82"
    if program_1:
        if v82['program_1'] > float(program_1):
            print ("Update available", program_1, "-->", v82[program_1])

等等等等

虽然我的火车会像

if program_1:
    if v[program_main] > float(program_1):
        print('Update available", program_1, "-->", v[program_main])

等等等等

我确信有更好的方法来完成整个设置,但这是我第一个正确的 Python 脚本之一,所以我很高兴将其归结为 noobish-ness,只是想知道正确的方法我正在努力实现的目标是.

I'm sure there's a much better way to do this entire setup, but this is one of my first proper python scripts so I'm happy to chalk it up to noobish-ness, just wanted to know what the right way of doing what I'm trying to achieve is.

推荐答案

您可以将您的函数放入字典中:

You can put your functions into a dictionary:

per_version = {
    '83': v83,
    '82': v82,
}

并简单地使用它来将字符串映射到函数:

and simply use that to map string to function:

per_version[program_main]('program_1')

但是,您可能希望改为参数化您的版本函数;make one 将版本作为参数的函数:

However, you may want to instead parameterise your version functions; make one function that takes the version as a parameter:

def program_check(version, program_1=None, program_2=None, program_3=None):
   # ...

然后查找每个 program_x 参数的默认值,而不是基于版本,再次从字典中查找.

which then looks up default values per program_x parameter based no the version, again from a dictionary perhaps.

这篇关于Python中变量内的变量(3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆