2016-09-28 73 views
4

讓我們假設我有以下列表:如何將字符串插入字符串列表的每個標記?

l = ['the quick fox', 'the', 'the quick'] 

我想列表中的每個元素轉變成一個網址如下:

['<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>','<a href="http://url.com/fox">fox</a>', '<a href="http://url.com/the">the</a>','<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>'] 

到目前爲止,我試過如下:

list_words = ['<a href="http://url.com/{}">{}</a>'.format(a, a) for a in x[0].split(' ')] 

問題是,上面的列表理解只是做了列表的第一個元素的工作:

['<a href="http://url.com/the">the</a>', 
'<a href="http://url.com/quick">quick</a>', 
'<a href="http://url.com/fox">fox</a>'] 

我也試圖與一個map但是,它沒有工作:

[map('<a href="http://url.com/{}">{}</a>'.format(a,a),x) for a in x[0].split(', ')] 

如何創建句子列表的令牌,鏈接任何想法?

回答

5

你接近,你限制你的理解到x[0].split內容,即你是通過l要素缺一個for循環:

list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for x in l for a in x.split()] 

這個工程,因爲"string".split()產生了一個元素列表。

這可以看方式漂亮如果你定義的理解外的格式字符串和使用參數的通知format的位置指數{0}(所以你不需要做format(a, a)):

fs = '<a href="http://url.com/{0}">{0}</a>' 
list_words = [fs.format(a) for x in l for a in x.split()] 

隨着map你可以得到一個醜小鴨太多,如果你喜歡:

list(map(fs.format, sum(map(str.split, l),[]))) 

在這裏,我們sum(it, [])扁平化鋰列表mapsplit產生然後將fs.format映射到相應的展平列表。結果都是一樣的:

['<a href="http://url.com/the">the</a>', 
'<a href="http://url.com/quick">quick</a>', 
'<a href="http://url.com/fox">fox</a>', 
'<a href="http://url.com/the">the</a>', 
'<a href="http://url.com/the">the</a>', 
'<a href="http://url.com/quick">quick</a>'] 

與理解去,明顯

+0

感謝您的幫助傢伙! – tumbleweed

2
list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for item in l for a in item.split(' ')] 
+0

如果你真的給答案添加一點解釋,它通常會更好:-) –

2

一個班輪

list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for a in [i for sub in [i.split() for i in l] for i in sub]] 

在步驟

您可以分割清單:

l = [i.split() for i in l] 

,然後壓平:

l = [i for sub in l for i in sub] 

結果:

>>> l 
['the', 'quick', 'fox', 'the', 'the', 'quick'] 

然後:

list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for a in l] 

你最終會採取:

>>> list_words 
['<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>', '<a href="http://url.com/fox">fox</a>', '<a href="http://url.com/the">the</a>', '<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>']