我想知道如何使用列表理解替换列表的值。例如
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'
我想知道如何将其转换为列表理解格式。
最佳答案
你可以做一个嵌套的列表理解:
theList = [[1,2,3],[4,5,6],[7,8,9]]
[[x if x % 2 else 'hey' for x in sl] for sl in theList]
返回
[[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
关于python - 如何在 python3 中使用列表理解替换值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48799698/