[英]Joining a list of python objects with __str__ method
I've already looked at this question on representing strings in Python but my question is slightly different. 我已经看过这个关于在Python中表示字符串的问题,但我的问题略有不同。
Here's the code: 这是代码:
>>> class WeirdThing(object):
... def __init__(self):
... self.me = time.time()
... def __str__(self):
... return "%s" % self.me
... def __repr__(self):
... return ";%s;" % self.me
...
>>> weird_list = [WeirdThing(), WeirdThing(), WeirdThing()]
>>> print weird_list
[;1302217717.89;, ;1302217717.89;, ;1302217717.89;]
>>> "\n".join(weird_list)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: sequence item 0: expected string, WeirdThing found
I realize that this works: 我意识到这有效:
>>> "\n".join(str(wi) for wi in weird_list)
'1302217717.89\n1302217717.89\n1302217717.89'
>>>
Still it would be nice to avoid doing that every time I want to join the objects together. 每次我想要将对象连接在一起时,避免这样做仍然会很好。 Is it simply not possible?
这根本不可能吗?
You have to stringify your objects before you can join them. 您必须先对对象进行字符串化,然后才能加入它们。 This is because
str.join
expects a series of strings, and you must give it a series of strings. 这是因为
str.join
需要一系列字符串,你必须给它一系列字符串。
For the sake of less typing at the cost of readability, you can do "\\n".join(map(str, list_of_things)
. 为了便于输入而不考虑可读性,可以执行
"\\n".join(map(str, list_of_things)
。
There are probably no amazing way. 可能没什么惊人的方式。
def strjoin(glue, iterable):
return glue.join(str(s) for s in iterable)
"...it would be nice to avoid doing that every time..." “......每次都避免这样做会很好......”
You want to avoid repeating that same code multiple times? 您想避免多次重复相同的代码吗? Then use a function;:
然后使用函数;:
def join_as_str(alist):
return "\n".join(str(item) for item in alist)
Would it work for you if you added an __add__
method? 如果添加
__add__
方法,它会对你__add__
吗? Eg, 例如,
from operator import add
from random import randint
class WeirdThing(object):
def __init__(self,me=None):
self.me = me if me else chr(randint(97,122))
def __str__(self):
return "%s" % self.me
def __repr__(self):
return ";%s;" % self.me
def __add__(self,other):
new_me = add(str(self.me),str(other.me))
return WeirdThing(new_me)
weird_list = [WeirdThing(), WeirdThing(), WeirdThing()]
print weird_list
gives, 给,
[;y;, ;v;, ;u;]
and this, 和这个,
strange_thing = reduce(add,weird_list)
print strange_thing
gives, 给,
yvu
You technically aren't joining the list of python objects, just their string representation. 从技术上讲,您不会加入python对象列表,只是它们的字符串表示。
>>> reduce(lambda x,y: "%s\n%s" % (x,y), weird_list)
'1302226564.83\n1302226564.83\n1302226564.83'
>>>
This works as well but doesn't look any nicer: 这也有效,但看起来并不好看:
>>> a = ""
>>> for x in weird_list:
... a+="%s\n" % x
...
>>> print a
1302226564.83
1302226564.83
1302226564.83
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.