How to insert a string in each token of a list of strings?

Suppose I have the following list:

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

I would like to convert each list item to url as follows:

['<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>']

So far I have tried the following:

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

The problem is that the above list comprehension just does the job for the first element of the list:

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

I also tried with map, but this did not work:

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

Any idea on how to create such links from offer list tokens?

+4
source share
3 answers

You were close, you limited your understanding to content x[0].split, that is, you were absent from the cycle forthrough the elements 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),[])))

we 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>']

, .

+5
list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for item in l for a in item.split(' ')]
+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>']
+2

Source: https://habr.com/ru/post/1656137/


All Articles