开发者

Shortest/Best way to do this list task in Python

开发者 https://www.devze.com 2023-02-13 21:58 出处:网络
I\'m learning Python. I\'d like to do the following task: Input: a list: e.g., [\'a\', \'b\', \'c\'] Output: a single string that concatenate all elements in the list, while each element is modifed

I'm learning Python. I'd like to do the following task:

  • Input: a list: e.g., ['a', 'b', 'c']
  • Output: a single string that concatenate all elements in the list, while each element is modifed in the same way for all elements.

For example, I'd like to add "-temp" to each element in the list. So, the output would be:

"a-temp b-temp c-temp"

Of co开发者_如何学JAVAuse, I can write C/C++ style. But, is there more elegant or interesting way in Python?


>>> ' '.join( x+'-temp' for x in ['a', 'b', 'c'] )
'a-temp b-temp c-temp'


List comprehensions are your friend:

lst =  ['a', 'b', 'c']
print ' '.join(['%s-temp' % item for item in lst])


Use list comprehensions when you need to access and use each element of a list. Example:

l = ['a', 'b', 'c']
' '.join([element + '-temp' for element in l])


Here you go:

s = " ".join(["%s-temp" % s for s in thelist])

That contains a list comprehension that maps the elements of thelist through a string interpolation, generating a new list. That is then joined with a space in between to get the final string.


 '-temp'.join(list) 

I believe will do it.


Almost:

 '-temp '.join(['a','b','c'])+'-temp'


You can use map function as below:

l = ['a','b','c']
map((lambda s: s + '-temp'), l)
0

精彩评论

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