【问题标题】:how to loop list to pass string to function name in python如何循环列表以将字符串传递给python中的函数名
【发布时间】:2014-11-07 20:13:14
【问题描述】:

我正在尝试找到最有效的方法来创建不同的函数名称 myfunction_a ,.. b , c 代码略有不同(输入文件名 'app/data/mydata_a. csv' ) 所以下面是我得到的 a 函数

def myfunction_a(request):

    os.getcwd()  # Should get this Django project root (where manage.py is)
    fn = os.path.abspath(os.path.join(os.getcwd(),'app/data/mydata_a.csv'))
    # TODO: Move to helper module
    response_data = {}
    data_format = 'tsv'
    if data_format == 'json':
        with open(fn, 'rb') as tsvin:
            tsvin = csv.reader(tsvin, delimiter='\t')

            for row in tsvin:
                print 'col1 = %s  col2 = %s' % (row[0], row[1])
                response_data[row[0]] = row[1]
        result = HttpResponse(json.dumps(response_data), content_type = 'application/json')
    else:
        with open(fn, 'rb') as tsvin:
            buff = tsvin.read()
        result = HttpResponse(buff, content_type = 'text/tsv')
    return result

我希望能够遍历我的列表并创建多个函数名称:

mylist = ['a','b','c' ... 'z' ]

def myfunction_a(请求): ... ('app/data/mydata_a.csv') 退货要求

得到最终结果:

  • def myfunction_a => 采用 'app/data/mydata_a.csv'
  • def myfunction_b => 采用 'app/data/mydata_b.csv'
  • def myfunction_c => 采用 'app/data/mydata_c.csv'

现在我只是复制并粘贴并更改它。有更好的方法吗?任何建议将不胜感激。谢谢。

【问题讨论】:

  • 为什么需要这样做? mywiki.wooledge.org/XyProblem
  • @gnibbler 我在 Django 中使用这个函数名作为 views.py 的一部分,并使用 url 根据需要提取每个函数,从 Django 模板调用视图应用程序。

标签: python function


【解决方案1】:

你可以添加一个变量到一个字符串

"app/data/mydata_%s.csv" % (character)

所以

for character in mylist:
    print "app/data/mydata_%s.csv" % (character)

应该每次在%s的地方追加一个字符

因此,由于您希望每个函数都使用另一个字符串来获取另一个文件,因此您可以 做这样的事情:

def myfunction(label, request):
    return "app/data/mydata_%s.csv" % (label) 

所以您会在文档路径的末尾获得函数标签。既然你描述了你 只想更改名称使其等于函数标签,您只需要另一个参数而不是新的函数名称

【讨论】:

  • 嗨@muthan 这是其中的一部分,但我也在寻找创建该函数名称 def "myfunction_a" "myfunction_b" .. 以及。
  • 对于函数,你不能将 a,b,c 放入一个参数中,这样你就有一个像 def myfunction(character,request) 这样的函数调用,除了命名不同之外,函数每次都做相同的事情,这应该可以工作。我会将其添加到我的答案中。
【解决方案2】:

如果你必须有一个特殊的函数名,你可以这样做。虽然我不确定你为什么需要这样做。

import functools, sys
namespace = sys._getframe(0).f_globals

def myfunction(label, request):
    print request
    return "app/data/mydata_%s.csv" % (label)

my_labels = ['a','b','c']
for label in my_labels:
    namespace['myfunction_%s'%label] = functools.partial(myfunction, label)

print myfunction_a('request1')
print myfunction_b('request2')

输出是这样的:

request1
app/data/mydata_a.csv
request2
app/data/mydata_b.csv

或者更好的实现可能是:

class MyClass(object):
    def __init__(self, labels):
        for label in labels:
            setattr(self, label, functools.partial(self._myfunction, label))
    def _myfunction(self, label, request):
        print request
        return "app/data/mydata_%s.csv" % (label)

myfunction = MyClass(['a','b','c'])
print myfunction.c('request3')

输出是这样的:

request3
app/data/mydata_c.csv

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2021-05-31
    • 2016-01-12
    • 1970-01-01
    • 2021-06-21
    相关资源
    最近更新 更多