Python字典和items()

2024-04-20 04:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的理解是.items()只适用于python字典

但是,在下面运行良好的代码中,.items()函数似乎对字符串可用(此代码用于doc2vec的预处理阶段)

我已经看了一段时间了,我不明白为什么.items()在这段代码中可以工作

在代码中,“sources”只是一个实例的属性。但是它可以调用.items()

我错过了什么

class LabeledLineSentence(object):

    def __init__(self, sources):
        self.sources = sources

        flipped = {}

        # make sure that keys are unique
        for key, value in sources.items():
            if value not in flipped:
                flipped[value] = [key]
            else:
                raise Exception('Non-unique prefix encountered')

Tags: 实例key函数字符串代码inself字典
2条回答

给定的代码只指定源是实例的属性。它没有指定它的类型。事实上,它可以是在创建LabeledLineSession实例时指定的任何类型

i1 = LabeledLineSentence('sample text') # sources is now a string. Throws error!
i2 = LabeledLineSentence({}) # source is a now a dictionary. No error!

请注意,LabeledLineSequence实现希望sources参数是字典

.items()可用于任何具有items方法的类。例如,我可以定义

class MyClass:
    def items(self):
        return [1,2,3,4]

然后跑

mc = MyClass()
for i in mc.items(): print(i)

大概您的sources对象属于具有这样一个属性的类。但我们不知道是什么,因为它是LabeledLineSentence构造函数的参数

你能给我们指出完整的源代码吗?这样我们就可以看到传递的信息了

相关问题 更多 >