我想知道如何使用列表理解来替换列表的值。例如
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 - “If there is one thing developers like less than writing documentation, it’响应不必要的升级[…],并且过多的升级使开发人员感到厌倦。”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48799698/