如何使用python3中的列表解析替换值?

use*_*333 6 python list-comprehension list python-3.x

我想知道如何使用列表理解来替换列表的值.例如

theList = [[1,2,3],[4,5,6],[7,8,9]]
newList = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(theList)):
  for j in range(len(theList)):
    if theList[i][j] % 2 == 0:
      newList[i][j] = 'hey'
Run Code Online (Sandbox Code Playgroud)

我想知道如何将其转换为列表理解格式.

Ale*_*lex 6

你可以做一个嵌套列表理解:

theList = [[1,2,3],[4,5,6],[7,8,9]]
[[x if x % 2 else 'hey' for x in sl] for sl in theList]
Run Code Online (Sandbox Code Playgroud)

返回

[[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
Run Code Online (Sandbox Code Playgroud)