Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表中的一个值映射到另一个值_Python_List_Mapping - Fatal编程技术网

Python 将列表中的一个值映射到另一个值

Python 将列表中的一个值映射到另一个值,python,list,mapping,Python,List,Mapping,在Python列表中,如何将一个值的所有实例映射到另一个值 例如,假设我有以下列表: x = [1, 3, 3, 2, 3, 1, 2] 现在,也许我想将所有1更改为'a',将所有2更改为'b',将所有3更改为'c',以创建另一个列表: y = ['a', 'c', 'c', 'b', 'c', 'a', 'b'] 我如何才能优雅地进行映射?您应该使用字典和: 字典充当转换为内容的转换表。另一种解决方案是使用内置函数,将函数应用于列表: In [255]: x = [1, 3, 3, 2,

在Python列表中,如何将一个值的所有实例映射到另一个值

例如,假设我有以下列表:

x = [1, 3, 3, 2, 3, 1, 2]
现在,也许我想将所有
1
更改为
'a'
,将所有
2
更改为
'b'
,将所有
3
更改为
'c'
,以创建另一个列表:

y = ['a', 'c', 'c', 'b', 'c', 'a', 'b']

我如何才能优雅地进行映射?

您应该使用字典和:


字典充当转换为内容的转换表。

另一种解决方案是使用内置函数,将函数应用于列表:

In [255]: x = [1, 3, 3, 2, 3, 1, 2]

In [256]: y = ['a', 'c', 'c', 'b', 'c', 'a', 'b']

In [257]: [dict(zip(x,y))[i] for i in x]
Out[257]: ['a', 'c', 'c', 'b', 'c', 'a', 'b']
>>> x = [1, 3, 3, 2, 3, 1, 2]
>>> subs = {1: 'a', 2: 'b', 3: 'c'}
>>> list(map(subs.get, x)) # list() not needed in Python 2
['a', 'c', 'c', 'b', 'c', 'a', 'b']

这里,
dict.get
方法被应用于列表
x
,每个数字在
subs

中被交换为相应的字母,我也可以对布尔值执行同样的操作吗?例如,
d={True:'a',False:'b'}
@Karnivaurus注意到,映射/转换仅仅是x中i的
f(i)
,其中示例中
f(i)->d[i]
。转换只使用应用于每个
i
f(i)
的结果。然后
f(i)
可以用“返回'a'表示1,返回'b'表示2..”的行为来描述,这可以通过多种方式实现,包括字典查找。如果我正确阅读了问题,则不会给出
y
,但映射是正确的。@LukasGraf:这一点很好。也许像ajcr建议的那样,一个
dict
会更好
>>> x = [1, 3, 3, 2, 3, 1, 2]
>>> subs = {1: 'a', 2: 'b', 3: 'c'}
>>> list(map(subs.get, x)) # list() not needed in Python 2
['a', 'c', 'c', 'b', 'c', 'a', 'b']