I have a nested list which looks like this:
l = [[['0.056*"googl"'], ['0.035*"facebook"']], #Index 0
[['0.021*"mensch"'], ['0.012*"forsch"']], #Index 1
[['0.112*"appl"'], ['0.029*"app"']], # Index 2
[['0.015*"intel"'], ['0.015*"usb"']]] #Index 3
Now I want to append the Index (and the word Topic) of the sublists into the individual sublists like this:
nl = [[['0.056*"googl"', 'Topic 0'], ['0.035*"facebook"', 'Topic 0']],
[['0.021*"mensch"', 'Topic 1'], ['0.012*"forsch"', 'Topic 1']],
[['0.112*"appl"', 'Topic 2'], ['0.029*"app"', 'Topic 2']],
[['0.015*"intel"', 'Topic 3'], ['0.015*"usb"', 'Topic 3']]]
How can I do this?
asked Jan 28, 2020 at 11:49
-
Sorry my bad, I removed them with regex in my code. Will change the OP.gython– gython2020年01月28日 12:34:04 +00:00Commented Jan 28, 2020 at 12:34
2 Answers 2
Use:
nl = [[[*x, 'Topic %s' % idx] for x in i] for idx, i in enumerate(l)]
Or use:
nl = [[x + ['Topic %s' % idx] for x in i] for idx, i in enumerate(l)]
And now:
print(nl)
Is:
[[['0.056*"googl"', 'Topic 0'], [' 0.035*"facebook"', 'Topic 0']], [['0.021*"mensch"', 'Topic 1'], [' 0.012*"forsch"', 'Topic 1']], [['0.112*"appl"', 'Topic 2'], [' 0.029*"app"', 'Topic 2']], [['0.015*"intel"', 'Topic 3'], [' 0.015*"usb"', 'Topic 3']]]
answered Jan 28, 2020 at 11:51
-
Hi @U10 -Forward, thanks for your answer. One more question: How would I have to change the code if the sublists looked like this:
[[['0.056', 'googl']], [['0.035', 'facebook']]]
?gython– gython2020年01月28日 12:41:14 +00:00Commented Jan 28, 2020 at 12:41 -
@gython ask a new questionU13-Forward– U13-Forward2020年01月29日 01:26:32 +00:00Commented Jan 29, 2020 at 1:26
You can do it with for
loop
for i in range(len(l)):
l[i][0].append(f'Topic {i}')
l[i][1].append(f'Topic {i}')
answered Jan 28, 2020 at 11:53
lang-py