简体   繁体   English

谁能告诉我我做错了什么,字典与 Python 中的列表?

[英]Can anyone tell me what I am doing wrong, dictionary vs list in Python?

I am trying to initialize a dictionary as a attribute in my object and trying to use defaultdict.我正在尝试将字典初始化为我的 object 中的属性并尝试使用 defaultdict。 Somehow, it works on Mac not Windows.不知何故,它适用于 Mac 而不是 Windows。 What I want is:我想要的是:

1 {'1':[], '2':[]}
2 {'1':[], '2':[]}

Here is what I ve done so far.这是我到目前为止所做的。

class A:
    
    def __init__(self, id):
        self.id = id
        self.x = self.y

    @property
    def y(self):
        ref = defaultdict(list)
        ls = ['1', '2']
        for i in ls:
            ref[i] = []
        return ref

    def __str__(self):
        return f'{self.id}, {self.x}'.format(self=self)

def main():
    for i in range(2):
        me = A(i)
        print(me)

if __name__ == '__main__':
    main()

Error message I'm having is:我遇到的错误消息是:

KeyError: "'23'" 

or some other numbers and varies every time.或其他一些数字,并且每次都不同。 The self.y function works when I am just directly accessing it. self.y function 在我直接访问它时工作。 Like:喜欢:

    for i in range(2):
        me = A(i)
        print(me.y)

Of course, before that I set:当然,在此之前我设置:

class A: 
    
        def __init__(self, id):
            self.id = id    
            self.x =  [] 

then然后

    for i in range(2):     
        me = A(i)
        print(me)

I get我明白了

1 []
2 []

but I want但我想要

1 {'1':[]}
2 {'2':[]}

so I can add some values in dictionary values.所以我可以在字典值中添加一些值。

What am I doing wrong?我究竟做错了什么? It seems there is a problem in return values when I sign {} instead of [] .当我签署{}而不是[]时,返回值似乎存在问题。 Is there a way to figure out or work around it?有没有办法弄清楚或解决它?

You are using both f"" and str.format , so you do formatting twice.您同时使用f""str.format ,因此您进行了两次格式化。 str.format interprets 1 {'1':[]} as template string and tries to expand '1' , thus a KeyError . str.format1 {'1':[]}解释为模板字符串并尝试扩展'1' ,因此是KeyError

Thanks great responses and recommendations.感谢伟大的回应和建议。 Yes, I am sure many of you see 'weird' stuff in my codes because I do not fully explained the purposes.是的,我相信你们中的许多人在我的代码中看到了“奇怪”的东西,因为我没有完全解释这些目的。 Yes, I should not use defaultdict instead of a simple dict.是的,我不应该使用 defaultdict 而不是简单的 dict。 Yes, I was using f'' also.format().是的,我正在使用 f'' also.format()。 Thanks for the lesson.谢谢你的课。

What works across platform is could be simple but want your feedback.跨平台的工作可能很简单,但需要您的反馈。 ''' '''

class A: class

    def __init__(self, x):
        self.x = x   # id
        self.y = {}  # key = days, value = activities 
    
    def make_day(self):
    ''' each inst accepts random days and days have random activities'''
        random_days =  ['sorted','string','days','sampled','from','week']
        for each_day in random_days:
            self.y[each_day] = []
        return self.y
    
     def __str__(self):
        return f'%d, %s'%(self.x, self.y)

def main(): for i in range(2): a = A(i) a.make_day() print(a) if name == ' main ': main() def main(): for i in range(2): a = A(i) a.make_day() print(a) if name == ' main ': main()

0, {'sorted': [], ..., 'week': []} 1, {'sorted': [], ..., 'week': []} 0, {'sorted': [], ..., 'week': []} 1, {'sorted': [], ..., 'week': []}

''' '''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人可以告诉我我做错了什么吗? - Can someone tell me what am I doing wrong? 在 GOOGLE COLAB 中运行此 python 代码时,它向我显示错误。 谁能告诉我我做错了什么并分享更正的代码? - On running this python code in GOOGLE COLAB, it showing me error. Can anyone please tell what am i doing wrong and share a corrected code? 有人可以告诉我我做错了什么新到 Python - Can someone please tell me what am I doing wrong New to Python 谁能告诉我我在做什么错? ast.literal_eval格式错误的节点或字符串python3 - can anyone tell me what i'm doing wrong? ast.literal_eval malformed node or string python3 谁能告诉我这个列表理解有什么问题? - Can anyone tell me what is wrong with this list comprehension? 有人可以告诉我我做错了什么[暂停] - Can someone tell me what I'm doing wrong [on hold] 谁能解释我做错了什么 - Can anyone explain what am i doing wrong 我的第一个python程序:你能告诉我我做错了什么吗? - My first python program: can you tell me what I'm doing wrong? 我无法在Python中正确定义一个函数。 谁能告诉我我要去哪里错了? - I can't properly define a function in Python. Can anyone tell me where I am going wrong? 我不明白为什么这段代码不起作用! 有人可以告诉我我做错了吗? - I don't see why this code is not working! can someone please tell me what i am doing wrong?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM