I'm trying to update all list items that are inside a list. Better to say it's a matrix. I'm building it like that:
grids = [["#"] * grid_size for _ in range(grid_size)]
Output if my grid for a size 4:
[['#', '#', '#', '#'],
['#', '#', '#', '#'],
['#', '#', '#', '#'],
['#', '#', '#', '#']]
Next to that I have a list of dictionaries with several words inside. Code: all_words = [x for x in words]
Output of all words:
...
...
{'definition': 'Maladie virale caractérisée par une éruption de vésicules '
'disposées sur le trajet des nerfs sensitifs.',
'word': 'ZONA',
'word_length': Decimal('4')},
{'definition': "Partie d'une surface sphérique comprise entre deux plans "
'parallèles.',
'word': 'ZONE',
'word_length': Decimal('4')},
{'definition': 'Musique de danse très rythmée, originaire de la Martinique.',
'word': 'ZOUK',
'word_length': Decimal('4')},
{'definition': 'Naïf, niais.', 'word': 'ZOZO', 'word_length': Decimal('4')}]
What I would like to do is to replace the "#" in the matrix in order to add the 'word' that are in my dictionaries. Here for the example 'ZONA', 'ZONE', 'ZOUK' and 'ZOZO' that are my four last words.
Desired output:
[['Z', 'O', 'N', 'A'],
['Z', 'O', 'N', 'E'],
['Z', 'O', 'U', 'K'],
['Z', 'O', 'Z', 'O']]
The best would be of course to add only these four words so that the matrix doesn't expand more than it is. I tried with a list comprehension inside another list comprehension but I'm messing everything up...
Thanks a lot for your help ! Btv-
CodePudding user response:
I think this is what you have right now
all_words = [ {'definition': 'Maladie virale caracterisee par une eruption de vesicules '
...: 'disposees sur le trajet des nerfs sensitifs.',
...: 'word': 'ZONA',
...: 'word_length': Decimal('4')},
...: {'definition': "Partie d'une surface spherique comprise entre deux plans "
...: 'paralleles.',
...: 'word': 'ZONE',
...: 'word_length': Decimal('4')},
...: {'definition': 'Musique de danse tres rythmee, originaire de la Martinique.',
...: 'word': 'ZOUK',
...: 'word_length': Decimal('4')},
...: {'definition': 'Naif, niais.', 'word': 'ZOZO', 'word_length': Decimal('4')}]
First get a list of only the words
only_words = [word["word"] for word in all_words]
Then use list() to make the word into a list of individual letters
[list(word) for word in only_words]
[['Z', 'O', 'N', 'A'],
['Z', 'O', 'N', 'E'],
['Z', 'O', 'U', 'K'],
['Z', 'O', 'Z', 'O']]
CodePudding user response:
You could typecast the word to list using list()
directly to create a 2D list instead of replacing the hash in the created list.
all_words = ['ZONA' , 'ZONE', 'ZOUK', 'ZOZO']
print([list(word) for word in all_words])
Output:
[['Z', 'O', 'N', 'A'], ['Z', 'O', 'N', 'E'], ['Z', 'O', 'U', 'K'], ['Z', 'O', 'Z', 'O']]