[英]how to change a list to a specific string.
class Bag:
def __init__(self, i=None):
self.bag = []
if i == None:
pass # i is None, do nothing after create empty bag
elif type(i)==list:
self.bag.extend(i) # append whole list i into bag with extend method
else:
self.bag.append(i) # append single item i into bag
def __repr__(self):
for s in self.bag :
return s
def __str__(self):
for s in self.bag :
return s
In the __str__method. 在__str__方法中。 It supposed to return a string.
它应该返回一个字符串。
The list is Bag(['a', 'c', 'b', 'b', 'd', 'd', 'd']). 列表为Bag(['a','c','b','b','d','d','d'])。 And
和
__str__ is supposed to return Bag(a[1], c[1], b[2], d[3])
Can anyone tell me how to make it work? 谁能告诉我如何使其运作? Many thanks.
非常感谢。
You can use a collections.Counter
here to help: 您可以在这里使用
collections.Counter
来帮助:
def __str__(self):
counts = Counter(self.bag)
count_str = ','.join('{}[{}]'.format(k, v) for k, v in counts.items())
return 'Bag({})'.format(count_str)
The great thing about this is that the counter does all the work of figuring out how many of each item are in your bag
. 最好的是,柜台可以完成所有工作,弄清楚您的
bag
有多少件物品。 All the rest of it is just formatting details. 所有其余的只是格式化细节。 One downside is that the counter is not ordered.
缺点之一是没有订购计数器。 If you want an order, you could use the
.most_common
method (which will order the counts from most common to least-common), or you could use something like an ordered unique recipe to figure out how you want to iterate over the counter. 如果要订购,可以使用
.most_common
方法(将从最常见到最不常见的计数顺序),或者可以使用诸如订购的唯一配方之类的方法来确定如何在柜台上进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.