2012-11-11 23 views
15

已經通過Stack Exchange做了一些搜索回答的問題,但一直無法找到我在找的內容。將同一個字符串添加到列表中的所有項目

考慮以下列表:

a = [1, 2, 3, 4] 

我將如何創建:

a = ['hello1', 'hello2', 'hello3', 'hello4'] 

謝謝!

+1

你能編輯您的帖子把周圍的報價字符串? – Nicolas

+0

對不起 - 對Python仍然很新鮮! –

回答

32

使用list comprehension

['hello{0}'.format(i) for i in a] 

列表解析,您可以在適用序列的表達每一個元素。

演示:

>>> a = [1,2,3,4] 
>>> ['hello{0}'.format(i) for i in a] 
['hello1', 'hello2', 'hello3', 'hello4'] 
+0

哦,甜蜜!非常感謝。我確信Python中有這樣一個有用的構造來完成這種事情。將消失,閱讀更多關於列表理解。 –

1

使用list comprehension

In [1]: a = [1,2,3,4] 

In [2]: ["hello" + str(x) for x in a] 
Out[2]: ['hello1', 'hello2', 'hello3', 'hello4'] 
+0

這是比第一個答案更多或更少的pythonic方式?我覺得它更容易閱讀。這與引擎蓋下的格式方法基本相同? –

+2

不能說它是pythonic,但它需要首先將'int'轉換爲'string',這可以通過'format()'方便地處理,所以轉到基於'format()'的答案。 –

+0

謝謝@AshwiniChaudhary。很有幫助。 –

7

還有一個選擇是使用built-in map function

a = range(10) 
map(lambda x: 'hello%i' % x, a) 

編輯按WolframH評論:

map('hello{0}'.format, a) 
+0

謝謝。男人,我有很多東西要學。 –

+0

歡迎 –

+3

或者使用map('hello {0}'.format,a)',特別是如果你還不知道'lambda'的話。注意:在Python 3.x中'map'不會返回一個'list'(但是另一個可迭代的對象,它可以使用list()轉換爲'list'。 – WolframH

相關問題