Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用类型(a)作为字典键是否合理?_Python_Dictionary_Pygments - Fatal编程技术网

Python 使用类型(a)作为字典键是否合理?

Python 使用类型(a)作为字典键是否合理?,python,dictionary,pygments,Python,Dictionary,Pygments,我试图根据文件类型将其存储在字典中。为此,我使用了pygmentsAPI,如下所示: #self.files字典的初始化 self.files=dict() #扫描和分类文件 对于文件中的文件: lexer=guess\u lexer\u用于文件名(文件,无) 如果在self.files中键入(lexer): self.files[类型(lexer)].append(文件) 其他: self.files[类型(lexer)]=[文件] 但是,现在,当通过pylint3传递此代码时,我收到一条警

我试图根据文件类型将其存储在字典中。为此,我使用了
pygments
API,如下所示:

#self.files字典的初始化
self.files=dict()
#扫描和分类文件
对于文件中的文件:
lexer=guess\u lexer\u用于文件名(文件,无)
如果在self.files中键入(lexer):
self.files[类型(lexer)].append(文件)
其他:
self.files[类型(lexer)]=[文件]
但是,现在,当通过
pylint3
传递此代码时,我收到一条警告,告诉我应该使用
isinstance()
代替
type()
(单向类型检查)

到目前为止,解决此警告的最佳方法如下:

self.files=dict()
对于文件中的文件:
lexer=guess\u lexer\u用于文件名(文件,无)
如果self.files中的lexer.\uuuuu类\uuuuuu:
self.files[lexer.\uuuuuuuu类\uuuuuuu].append(文件)
其他:
self.files[lexer.\uuuuuu class\uuuuuu]=[file]
但是,它真的解决了问题吗?而且,我开始怀疑在字典中使用类型作为键是否足够健壮

那么,有没有更合适、更稳健的方法呢?欢迎使用具有良好参数的任何解决方案。

使用
type()
输出对象作为键就可以了。在这种情况下

我将使用或扩展列表值:

self.files = {}

for file in files:
    lexer = guess_lexer__for_filename(file, None)
    self.files.setdefault(type(lexer), []).append(file)

然而,在Python3上,您可以研究是否可以使用它来处理您的用例。它为给定的对象类型调用一个注册函数,该函数取自第一个参数,并支持子类。

singledispatch()很好,但它不适合我想要的用法。而且,我不知道
setdefault
/
defaultdict
技巧,我肯定会使用它。谢谢!
from collections import defaultdict

self.files = defaultdict(list)

for file in files:
    lexer = guess_lexer__for_filename(file, None)
    self.files[type(lexer)].append(file)