简体   繁体   English

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

[英]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.

相关问题 从包含 python 中的字符串和数字的列表中获取最小值和最大值,然后用这些值替换字符串? - Get minimum and maximum values from a list containing both strings and numbers in python and then replace the strings with these values? 使用python从字符串列表中提取数字 - extracting numbers from list of strings with python 从 Python 中的字符串列表中提取和舍入数字 - Extract and round numbers from list of strings in Python 从另一个列表替换 Python 列表中的项目 - Replace items in a Python list from another list 根据 Python 中另一个列表中的值替换字符串列表 - Replace a list of strings based on values in another list in Python 用另一个列表中的字符串替换一个列表中的字符串 - Replace strings in one list with strings in another list Python - 如何用另一个列表中的字符串值替换列表中存储的字符串的值? - Python - How do you replace the values of strings stored in a list with the string values from another list? Python-用数字替换列表中的电子邮件 - Python - Replace email from list by numbers 将列表中的字符串乘以另一个列表中的数字,逐个元素 - Multiplying strings in a list by numbers from another list, element by element 如何用另一个列表中的数字替换字符串中的数字? - How to replace numbers in a string with numbers from another list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM