gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:01:18 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com