从Python中的函数返回名称中的变量

Lud*_*oco 11 python function list

我正在尝试使用函数返回给定列表.

def get_ext(file_type):
    text = ['txt', 'doc']
    audio = ['mp3', 'wav']
    video = ['mp4', 'mkv']
    return ?????

get_ext('audio')  #should return de list ['mp3', 'wav']
Run Code Online (Sandbox Code Playgroud)

然后我被卡住了.这是一个扩展列表的简单/简短示例.最简单的方法是什么?

tim*_*geb 30

在大多数情况下,这样一个普通的字典就可以完成这项工作.

>>> get_ext = {'text': ['txt', 'doc'],
...            'audio': ['mp3', 'wav'],
...            'video': ['mp4', 'mkv']
... }
>>> 
>>> get_ext['video']
['mp4', 'mkv']
Run Code Online (Sandbox Code Playgroud)

如果你真的想要或需要一个功能(可能有正当理由)你有几个选择.最简单的一种是分配给get字典的方法.get_ext如果您没有使用幕后的字典,您甚至可以重新指定名称.

>>> get_ext = get_ext.get
>>> get_ext('video')
['mp4', 'mkv']
Run Code Online (Sandbox Code Playgroud)

None如果输入未知密钥,此功能将默认返回:

>>> x = get_ext('binary')
>>> x is None
True
Run Code Online (Sandbox Code Playgroud)

如果您想要KeyError代替未知密钥,请分配给get_ext.__getitem__而不是get_ext.get.

如果你想要一个自定义的默认值,一种方法是将字典包装在一个函数中.此示例使用空列表作为默认值.

def get_ext(file_type):
    types = {'text': ['txt', 'doc'],
             'audio': ['mp3', 'wav'],
             'video': ['mp4', 'mkv']
    }

    return types.get(file_type, [])
Run Code Online (Sandbox Code Playgroud)

但是,@ tomri_saadon给出了有效的注释,即types = ...每次函数调用都会执行赋值.如果这困扰你,你可以做些什么来解决这个问题.

class get_ext(object):
    def __init__(self):
        self.types = {'text': ['txt', 'doc'],
                      'audio': ['mp3', 'wav'],
                      'video': ['mp4', 'mkv']
        }

    def __call__(self, file_type):
        return self.types.get(file_type, [])

get_ext = get_ext()
Run Code Online (Sandbox Code Playgroud)

get_ext从这里你可以像常规函数一样使用,因为最后callables是callables.:)

请注意,此方法 - 除了self.types仅创建一次的事实- 具有相当大的优势,您仍然可以轻松更改函数识别的文件类型.

>>> get_ext.types['binary'] = ['bin', 'exe']
>>> get_ext('binary')
['bin', 'exe']
Run Code Online (Sandbox Code Playgroud)

  • 我建议你更进一步,*只是*使用字典,Ludoloco.为什么要浪费时间和打字功能呢?字典提供您正在寻找的功能.(正如这个答案雄辩地证明的那样) (4认同)
  • @TheNate你可以做出这个答案(我很惊讶没有一个答案能说明这一点).在函数中包装字典似乎只是使用圆括号而不是方括号而做了大量工作. (2认同)

Joe*_*don 9

如果你不想定义一个dictionaryin in @timgeb's answer,那么你可以调用local()它给你一个dictionary当前variables可用的.

def get_ext(file_type):
    text = ['txt', 'doc']
    audio = ['mp3', 'wav']
    video = ['mp4', 'mkv']
    return locals()[file_type]
Run Code Online (Sandbox Code Playgroud)

并且测试表明它有效:

>>> get_ext("text")
['txt', 'doc']
Run Code Online (Sandbox Code Playgroud)

  • 不,这有效,但这是一个可怕的方法.它利用了`locals()`返回字典的事实 - 使用真正的字典,这就是它们的用途! (13认同)
  • @alexis我不想说你的评论无效,但我无法理解“它利用了 locals() 返回字典这一事实”的推理。我们什么时候不“利用”知道调用的返回值可以做什么? (2认同)

归档时间:

查看次数:

3696 次

最近记录:

8 年 前