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

标签 python python-3.x list list-comprehension

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

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/

相关文章:

r - 将 data.frame 列表中的列表取消列出为单个 data.frame

python - 从 pandas df 中的特定值返回系列

python - AttributeError: 'tuple' 对象没有属性 'copy'

Python:在纯文本文件上写一个很长的连续数字列表

python - 如何在pytorch模型中加载检查点文件?

python - 如何从单独的键和值列表中制作字典(dict)?

python - 如何判断 boto.sqs.Queue.write() 是否成功?

python - 流水线操作时 Redis 中的 MemoryError

python - 正则表达式仅匹配从左到右阅读的最后一次出现

python - matlab 类似于 python 中的结构