Reputation: 95
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']]
Upvotes: 0
Views: 40
Reputation: 36380
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
.
Upvotes: 2
Reputation: 11
If you only want to do it with loop then try following:
labels = ['1','2','3']
sents = [['hi hello'], ['i was there'], ['this is a sent']]
output = []
for i in range(len(labels)):
output.append([ labels[i], sents[i][0] ])
print(output)
output:
[['1', 'hi hello'], ['2', 'i was there'], ['3', 'this is a sent']]
Upvotes: 1