我正在嘗試更新串列中的所有串列項。最好說它是一個矩陣。我是這樣構建的:
grids = [["#"] * grid_size for _ in range(grid_size)]
如果我的網格大小為 4,則輸出:
[['#', '#', '#', '#'],
['#', '#', '#', '#'],
['#', '#', '#', '#'],
['#', '#', '#', '#']]
接下來我有一個字典串列,里面有幾個詞。代碼:all_words = [x for x in words]
所有單詞的輸出:
...
...
{'definition': 'Maladie virale caracte?rise?e par une e?ruption de ve?sicules '
'dispose?es sur le trajet des nerfs sensitifs.',
'word': 'ZONA',
'word_length': Decimal('4')},
{'definition': "Partie d'une surface sphe?rique comprise entre deux plans "
'paralle?les.',
'word': 'ZONE',
'word_length': Decimal('4')},
{'definition': 'Musique de danse tre?s rythme?e, originaire de la Martinique.',
'word': 'ZOUK',
'word_length': Decimal('4')},
{'definition': 'Nai?f, niais.', 'word': 'ZOZO', 'word_length': Decimal('4')}]
我想要做的是替換矩陣中的“#”,以便添加我字典中的“單詞”。例如,'ZONA'、'ZONE'、'ZOUK' 和 'ZOZO' 是我最后說的四個字。
期望的輸出:
[['Z', 'O', 'N', 'A'],
['Z', 'O', 'N', 'E'],
['Z', 'O', 'U', 'K'],
['Z', 'O', 'Z', 'O']]
最好的當然是只添加這四個詞,這樣矩陣就不會擴展得更多。我嘗試在另一個串列理解中使用串列理解,但我把一切都搞砸了......
非常感謝你的幫助 !Btv-
uj5u.com熱心網友回復:
我想這就是你現在擁有的
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 個單詞
uj5u.com熱心網友回復:
您可以list()直接使用將單詞型別轉換為串列來創建 2D 串列,而不是替換已創建串列中的散列。
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']]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366585.html
