如何将字符串插入字符串列表的每个标记?

tum*_*eed 4 python string list-comprehension python-3.x

让我们假设我有以下列表:

l = ['the quick fox', 'the', 'the quick']
Run Code Online (Sandbox Code Playgroud)

我想将列表中的每个元素转换为URL,如下所示:

['<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>']
Run Code Online (Sandbox Code Playgroud)

到目前为止,我尝试了以下内容:

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

问题是上面的列表理解只是为列表的第一个元素工作:

['<a href="http://url.com/the">the</a>',
 '<a href="http://url.com/quick">quick</a>',
 '<a href="http://url.com/fox">fox</a>']
Run Code Online (Sandbox Code Playgroud)

我也试过了,map但它不起作用:

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

有关如何从句子列表的标记创建此类链接的任何想法?

Jim*_*ard 5

你很接近,你将你的理解限制在内容上x[0].split,即你错过了一个for循环l:

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

这是有效的,因为"string".split()产生一个元素列表.

如果您在理解之外定义格式字符串并使用位置索引通知参数(这样您不需要这样做),这看起来会更漂亮:{0}formatformat(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()]
Run Code Online (Sandbox Code Playgroud)

有了map你可以得到一个丑小鸭太多,如果你喜欢:

list(map(fs.format, sum(map(str.split, l),[])))
Run Code Online (Sandbox Code Playgroud)

这里我们sum(it, [])用yield生成列表列表map,split然后映射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>']
Run Code Online (Sandbox Code Playgroud)

显然,要理解这一点.