更新列表(矩阵)内的列表项

Update list items inside a list (matrix)

我正在尝试更新列表中的所有列表项。最好说它是一个矩阵。我正在这样构建它: grids = [["#"] * grid_size for _ in range(grid_size)]

如果我的网格尺寸为 4,则输出:

[['#', '#', '#', '#'],
 ['#', '#', '#', '#'],
 ['#', '#', '#', '#'],
 ['#', '#', '#', '#']]

旁边有一个字典列表,里面有几个单词。代码:all_words = [x for x in 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')}]

我想做的是替换矩阵中的“#”以添加我词典中的 'word'。这里举个例子 'ZONA'、'ZONE'、'ZOUK' 和 'ZOZO' 这是我的最后四个词。

期望的输出:

[['Z', 'O', 'N', 'A'],
 ['Z', 'O', 'N', 'E'],
 ['Z', 'O', 'U', 'K'],
 ['Z', 'O', 'Z', 'O']]

最好的当然是只添加这四个词,这样矩阵就不会扩展得比现在大。我尝试在另一个列表理解中使用列表理解,但我把一切都搞砸了...

非常感谢您的帮助! Btv-

我想这就是你现在拥有的

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

首先得到一个只有长度正确的单词的列表

only_words = [word["word"] for word in all_words if len(word["word"]) == 4]

然后使用 list() 将单词变成单个字母的列表

[list(word) for word in only_words[:4]]

[['Z', 'O', 'N', 'A'],
 ['Z', 'O', 'N', 'E'],
 ['Z', 'O', 'U', 'K'],
 ['Z', 'O', 'Z', 'O']]

编辑:我在第一个列表 comp 中添加了一个 if 语句,以按长度过滤单词。我看到你有一个“word_length”键,但我不熟悉 Decimal() 东西。

在第二个列表中,我使用列表切片只取前 n 个词

您可以直接使用 list() 将单词强制转换为列表以创建二维列表,而不是替换已创建列表中的散列。

all_words = ['ZONA' , 'ZONE', 'ZOUK', 'ZOZO']
print([list(word) for word in all_words])

输出:

[['Z', 'O', 'N', 'A'], ['Z', 'O', 'N', 'E'], ['Z', 'O', 'U', 'K'], ['Z', 'O', 'Z', 'O']]