I try create class, which will return values to pretty print. I found this post python __str__ for an object but I still can't understand how I can improve my class.
Here is my class:
class PrintList():
def __init__(self,lista):
self.lista=lista
def __str__(self):
if isinstance(x[0] in self.lista, dict): #for dicts in list
return ','.join(str(item),'->',str(item[x]) for x in item) for item in self.lista
else: # for variables in list
return ','.join(str(x) for x in self.lista)
and bug in first return:
return ','.join(str(item),'->',str(item[x]) for x in item) for item in self.lista
^
SyntaxError: invalid syntax
I try get the following result: key_dict->value_dict, etc.
You definitely have an invalid syntax in your comprehension/generator expression.
You should have written the expression as follows
return ','.join("{}->{}".format(item, item[x]) for x in item for item in self.lista)
Offtopic
As @MartijnPieter, for str.join
, its faster to use a list comprehension rather than a generator expression notably because it needs to generate the data before stitching them togeter (a two pass algorithm). Please refer list comprehension without [ ], Python
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.