简体   繁体   English

使用 function 到每个元素的元组字符串

[英]Tuple to string with a function to each element

There is a tuple (a, b, c) .有一个元组(a, b, c)

I need to get foo(a) + "\n" + foo(b) + "\n" + foo(c)我需要得到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):你可以这样做(如果 foo() 返回一个字符串):

tuple_ = (a,b,c)
"\n".join( foo(i) for i in tuple_ )

if foo() doesn't return a string:如果 foo() 不返回字符串:

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:如果为 python < 2.4 编写代码,请使用此代码,因为在 Python 2.4 中添加了生成器表达式:

tuple_ = (a,b,c)
"\n".join([ str(foo(i)) for i in tuple_ ])

As long as foo is a string:只要 foo 是一个字符串:

 "\n".join(map(foo,tup))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM