So I’m trying to concatenate a string to a list, but for some reason it only works for the very last values:
labels_and_sents = [] for l in labels: for s in sents: sl = [l] + s labels_and_sents.append(sl)
Input:
labels = ['1','2','3'] sents = [['hi hello'], ['i was there'], ['this is a sent']]
Output:
[['3', 'this is a sent']]
What i need is:
[['1', 'hi hello'],['2', 'i was there'],['3', 'this is a sent']]
Advertisement
Answer
For me this looks like task for map
, I would do
labels = ['1','2','3'] sents = [['hi hello'], ['i was there'], ['this is a sent']] output = list(map(lambda x,y:[x]+y,labels,sents)) print(output)
Output:
[['1', 'hi hello'], ['2', 'i was there'], ['3', 'this is a sent']]
Explanation: for every pair of corresponding elements from labels
and sents
I pack first one into list
and then concatenate with latter. This solution assumes len(labels)==len(sents)
does hold True
.