python输出列表的子列表_在子类中打印python列表

我有一个超类,如下所示:

class Container(object):

""" Holds hashable objects. Objects may occur 0 or more times """

def __init__(self):

""" Creates a new container with no objects in it. I.e., any object

occurs 0 times in self. """

self.vals = {}

def insert(self, e):

""" assumes e is hashable

Increases the number times e occurs in self by 1. """

try:

self.vals[e] += 1

except:

self.vals[e] = 1

def __str__(self):

s = ""

for i in sorted(self.vals.keys()):

if self.vals[i] != 0:

s += str(i)+":"+str(self.vals[i])+"

"

return s

我研究了一个子类:

class Bag(Container):

def remove(self, e):

""" assumes e is hashable

If e occurs in self, reduces the number of

times it occurs in self by 1. Otherwise does nothing. """

# write code here

if e in self.vals.keys():

self.vals[e] -= 1

def count(self, e):

""" assumes e is hashable

Returns the number of times e occurs in self. """

# write code here

if e not in self.vals.keys():

return 0

else:

return self.vals[e]

def __add__(self, other):

new_dict = other.vals

for e in self.vals.keys():

if e in other.vals.keys():

new_dict[e] += self.vals[e]

else:

new_dict[e] = self.vals[e]

return new_dict

def __str__(self):

s1 = ""

for i in sorted(self.new_dict.keys()):

s1 += str(i)+":"+str(self.new_dict[i])+"

"

return s1

运行测试用例时:

>一个=包()

> a.insert(3)

> a.insert(5)

> b =袋()

> b.insert(5)

> b.insert(5)

> b.insert(5)

>打印(a b)

我的输出是:

{3:1,5:4}

但是,预期输出应为:

3:1

5:4

如何获得正确的格式输出?非常感谢你!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值