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)
如果你不想定义一个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)
| 归档时间: |
|
| 查看次数: |
3696 次 |
| 最近记录: |