Tuple to string with a function to each element
There is a tuple (a, b, 开发者_JAVA技巧c)
.
I need to get foo(a) + "\n" + foo(b) + "\n" + foo(c)
How it can be done in a smart way, not manually?
You could do it this way (if foo() returns a string):
tuple_ = (a,b,c)
"\n".join( foo(i) for i in tuple_ )
if foo() doesn't return a string:
tuple_ = (a,b,c)
"\n".join( str(foo(i)) for i in tuple_ )
Edit
If writing for python < 2.4 use this since generator expressions were added in Python 2.4:
tuple_ = (a,b,c)
"\n".join([ str(foo(i)) for i in tuple_ ])
As long as foo is a string:
"\n".join(map(foo,tup))
精彩评论