1

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?

1
  • Sorry my bad, I removed them with regex in my code. Will change the OP. Commented Jan 28, 2020 at 12:34

2 Answers 2

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']]]
Sign up to request clarification or add additional context in comments.

2 Comments

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 ask a new question
1

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}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.