开发者

Tuple to string with a function to each element

开发者 https://www.devze.com 2023-03-08 10:30 出处:网络
There is a tuple (a, b, 开发者_JAVA技巧c). I need to get foo(a) + \"\\n\" + foo(b) + \"\\n\" + foo(c)

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))
0

精彩评论

暂无评论...
验证码 换一张
取 消