【问题标题】:Replace numbers in list with strings from another list in Python用 Python 中另一个列表中的字符串替换列表中的数字
【发布时间】:2019-12-15 17:08:54
【问题描述】:

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

data = [1, 2, 3, 1, 3]
labels = ['a','b','c']

如何将数据中的数字替换为标签,以便获得数据等于:

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

我尝试将标签设置为

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

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

【问题讨论】:

标签: python list replace


【解决方案1】:

带有偏移校正的简单列表理解(在这种情况下您不需要字典)

data = [1, 2, 3, 1, 3]
labels = ['a','b','c']    

>>> [labels[i-1] for i in data]
['a', 'b', 'c', 'a', 'c']

用字典:

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

【讨论】:

    【解决方案2】:

    您可以为此使用 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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-26
      • 2017-03-31
      • 2012-08-18
      • 2021-10-08
      • 2019-01-30
      • 2010-10-20
      相关资源
      最近更新 更多