1

I have a list of lists:

 batches = [['der\n', 'und\n', 'die\n', 'des\n', 'mit\n', 'in\n', 'nach\n', 'eine\n', 'wird\n', 'auf\n'], ['bei\n', 'im\n', 'den\n', 'das\n', 'von\n', 'einer\n', 'sich\n', 'dem\n', 'ist\n', 'über\n']

etc. There's 1 list of 10 lists, each containing 10 strings/tokens (I just provided a sample).

I have another list with some nouns and I want to change any string in batches if it matches a string in the list of nouns. But I want the structure of batches to remain the same, how can I do this?

    for x in batches:
        for y in x:
            if y.rstrip() in noun_list:
                y += '- this is a noun'

But this doesn't change anything. I also tried a list comprehension:

[''.join(y + '- this is a noun') if y.rstrip() in noun_list else [''.join(y)] for x in batches for y in x]

But the structure changes.

1 Answer 1

2

Strings in Python are immutable. You need to replace the list element, not update the temporary variable y. So you need the list index, which you can get with enumerate():

for x in batches:
    for i, y in enumerate(x):
        if y.rstrip() in noun_list:
            x[i] += '- this is a noun'
Sign up to request clarification or add additional context in comments.

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.