将列表中的数字替换为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']