如何在python3中使用列表理解替换值? [英] How to replace values using list comprehension in python3?

查看:48
本文介绍了如何在python3中使用列表理解替换值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering how would you can replace values of a list using list comprehension. e.g.

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'

我想知道如何将其转换为列表理解格式.

I want to know how I could convert this into the list comprehension format.

推荐答案

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

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

这篇关于如何在python3中使用列表理解替换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆