Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_Replace - Fatal编程技术网

将列表中的数字替换为Python中另一个列表中的字符串

将列表中的数字替换为Python中另一个列表中的字符串,python,list,replace,Python,List,Replace,我有一个数字列表和字符串列表: data = [1, 2, 3, 1, 3] labels = ['a','b','c'] 如何将数据中的数字替换为标签,以使数据等于: ['a','b','c','a','c'] 我试着将标签设置为 mappings [('a', 1), ('b',2), ('c',3)] 使用for循环替换数据变量,但我似乎无法替换列表。您可以使用numpy: import numpy as np import itertools np.array(labels)[[a

我有一个数字列表和字符串列表:

data = [1, 2, 3, 1, 3]
labels = ['a','b','c']
如何将数据中的数字替换为标签,以使数据等于:

['a','b','c','a','c']
我试着将标签设置为

mappings [('a', 1), ('b',2), ('c',3)]

使用for循环替换数据变量,但我似乎无法替换列表。

您可以使用numpy:

import numpy as np
import itertools
np.array(labels)[[a - b for a,b in zip(data, itertools.cycle([1]))]].tolist() 

#  ['a', 'b', 'c', 'a', 'c']

简单的列表理解和偏移量更正(在这种情况下,您不需要字典)

使用字典:

mappings = {1: 'a', 2: 'b', 3: 'c'}
>>> [mappings[i] for i in data]
['a', 'b', 'c', 'a', 'c']

类似于
[标签[i-1]表示数据中的i]
这是否应该回答您的问题?
mappings = {1: 'a', 2: 'b', 3: 'c'}
>>> [mappings[i] for i in data]
['a', 'b', 'c', 'a', 'c']