将多列表理解转换为单列表理解 [英] Multiple list comprehension into single list comprehension

查看:47
本文介绍了将多列表理解转换为单列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用列表理解来更改列表的值,我可以通过使用3个列表理解来做到这一点

I am trying to change the values of a list using list comprehension I can do that by using 3 list comprehensions

clr = [1,2,2,1,3,1,2,3]
clr= ["green"  if i== 1 else i for i in clr]
clr = ["yellow"  if i==2 else i for i in clr]
clr = ["black"  if i == 3 else i for i in clr]

使用下面提到的代码会引发语法错误

where as using the below mentioned code is throwing syntax error

clr = ["green"  if i== 1 else "yellow"  if i==2 else "black"  if i == 3 for i in clr]

还有更好的方法吗?

推荐答案

是.例如,您可以定义词典:

the_dic = { 1 : 'green', 2 : 'yellow', 3 : 'black' }

然后执行映射,例如:

clr = [the_dic.get(i,i) for i in clr]

或通过使用 map(..)(在可以用作生成器(因此很懒惰):

Or by using map(..) (in python-3.x this works as a generator (thus lazily):

clr = map(the_dic.get,clr)

如果 clr 中的元素不在词典中,则将插入 None .

This will insert Nones in case the element in clr is not in the dictionary.

因此,如果字典中的不是,这会将 i 添加到 clr 列表中.这是因为我们使用了 the_dic.get(i,i).第一个 i 是我们在字典中查找的 key .第二个 i 是后备"值:如果找不到密钥,我们返回的值.

This will thus add i to the clr list, if it is not in the dictionary. This is beause we use the_dic.get(i,i). The first i is the key we lookup in the dictionary. The second i is the "fallback" value: the value we return in case the key is not found.

如果您要过滤掉这些,可以使用:

clr = [the_dic[i] for i in clr if i in the_dic]

这篇关于将多列表理解转换为单列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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