-1

Suppose I have a main form named "main_form" and I have few more forms name like "w_main_form","g_main_form" etc etc which are based on "main_form" and they vary according to the 'category'.

Now is there any easy way to generate names of derived forms and how to call them.

Suppose the category is "iron" then the form name should be "w_main_form" and when the category is "coal" the form name should be "g_main_form".

4

2 回答 2

2
>>> main_name = "main_form"
>>> derived_names = []
>>> for prefix in ["w_", "g_"]:
    derived_names.append("%s%s" % (prefix, main_name))


>>> derived_names
['w_main_form', 'g_main_form']

或者,使用列表推导(我的首选方法):

>>> derived_names = ["%s%s" % (prefix, main_name) for prefix in ["w_", "g_"]]
>>> derived_names
['w_main_form', 'g_main_form']

一般来说,因此您可以自己应用相同的原则,您想根据函数来考虑要执行的转换f(main_name, data),以及data提供给它的 。在这种情况下,操作是“前置”(我用 实现"%s%s" % (prefix, main_name))并且数据是所有前缀。

编辑:是的。

>>> category_to_prefix = {'iron': 'w_', 'coal': 'g_'}
>>> def category_to_form_name(category):
    return '%s%s' % (category_to_prefix.get(category,""), 'main_form')

>>> category_to_form_name('iron')
'w_main_form'
>>> category_to_form_name('coal')
'g_main_form'
>>> category_to_form_name(None)
'main_form'

如果您正在寻找答案,请投票并接受答案(单击向上箭头和绿色复选标记)。

于 2012-07-01T16:41:21.593 回答
1

这将按照您的评论说明..

def generate_Name(base, category):
    if category == 'iron':
        derived_name = 'w_'+base
    elif category == 'coal':
        derived_name = 'g_'+base

    return derived_name


iron_form = generate_Name('main_form', 'iron')
coal_form = generate_Name('main_form', 'coal')

print iron_form
print coal_form

w_main_form
g_main_form
于 2012-07-01T16:47:31.443 回答