[英]Replace numbers in list with strings from another list in Python
I have a list of numbers and list of strings:我有一个数字列表和字符串列表:
data = [1, 2, 3, 1, 3]
labels = ['a','b','c']
How do I replace the numbers in data with the labels so that I will get data equals:如何用标签替换数据中的数字,以便获得数据等于:
['a','b','c','a','c']
I tried setting labels to我尝试将标签设置为
mappings [('a', 1), ('b',2), ('c',3)]
and using a for loop to replace the data variable but I cannot seem to replace a list.并使用 for 循环替换数据变量,但我似乎无法替换列表。
simple list comprehension with offset correction (in that case you don't need a dictionary)带有偏移校正的简单列表理解(在这种情况下,您不需要字典)
data = [1, 2, 3, 1, 3]
labels = ['a','b','c']
>>> [labels[i-1] for i in data]
['a', 'b', 'c', 'a', 'c']
with a dictionary:用字典:
mappings = {1: 'a', 2: 'b', 3: 'c'}
>>> [mappings[i] for i in data]
['a', 'b', 'c', 'a', 'c']
You can use numpy for this:您可以为此使用 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.