让我们假设我有以下列表:
l = ['the quick fox', 'the', 'the quick']
我想将列表的每个元素转换为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>']
到目前为止,我尝试了以下内容:
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(', ')]
如何从句子列表的标记创建这样的链接?
答案 0 :(得分:5)
你很接近,你将你的理解限制在x[0].split
的内容,即你错过了for
的{{1}}元素的l
循环:
list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for x in l for a in x.split()]
这是有效的,因为"string".split()
会产生一个元素列表。
如果您在理解之外定义格式字符串并使用位置索引{0}
通知format
参数,那么这可以看起来更漂亮(因此您不需要做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, [])
在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>']
理解,显然是。
答案 1 :(得分:2)
list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for item in l for a in item.split(' ')]
答案 2 :(得分: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>']