[英]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.format
将1 {'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.