且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python3中使用列表理解替换值?

更新时间:2023-11-23 15:21:34

您可以执行嵌套列表理解:

You can just do a nested list comprehension:

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]]