So I’m trying to concatenate a string to a list, but for some reason it only works for the very last values:
JavaScript
x
7
1
labels_and_sents = []
2
for l in labels:
3
for s in sents:
4
sl = [l] + s
5
6
labels_and_sents.append(sl)
7
Input:
JavaScript
1
3
1
labels = ['1','2','3']
2
sents = [['hi hello'], ['i was there'], ['this is a sent']]
3
Output:
JavaScript
1
2
1
[['3', 'this is a sent']]
2
What i need is:
JavaScript
1
2
1
[['1', 'hi hello'],['2', 'i was there'],['3', 'this is a sent']]
2
Advertisement
Answer
For me this looks like task for map
, I would do
JavaScript
1
5
1
labels = ['1','2','3']
2
sents = [['hi hello'], ['i was there'], ['this is a sent']]
3
output = list(map(lambda x,y:[x]+y,labels,sents))
4
print(output)
5
Output:
JavaScript
1
2
1
[['1', 'hi hello'], ['2', 'i was there'], ['3', 'this is a sent']]
2
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
.