如何使用字典来翻译/替换数组的元素?

编程入门 行业动态 更新时间:2024-10-24 08:32:57
本文介绍了如何使用字典来翻译/替换数组的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个numpy数组,其中包含数百个大写字母的元素,没有特定顺序

I have a numpy array, which has hundreds of elements which are capital letters, in no particular order

import numpy as np abc_array = np.array(['B', 'D', 'A', 'F', 'H', 'I', 'Z', 'J', ...])

此numpy.ndarray中的每个元素都是一个numpy.string_.

Each element in this numpy.ndarray is a numpy.string_.

我还有一个翻译词典",其中包含键/值对,以便大写字母对应于城市

I also have a "translation dictionary", with key/value pairs such that the capital letter corresponds to a city

transdict = {'A': 'Adelaide', 'B': 'Bombay', 'C': 'Cologne',...}

字典transdict中只有26对,但是numpy数组中有数百个字母我必须翻译.

There are only 26 pairs in the dictionary transdict, but there are hundreds of letters in the numpy array I must translate.

最有效的方法是什么?

What is the most efficient way to do this?

我已经考虑过使用numpy.core.defchararray.replace(a, old, new, count=None)[source],但这会返回ValueError,因为numpy数组的大小与字典键/值的大小不同.

I have considered using numpy.core.defchararray.replace(a, old, new, count=None)[source] but this returns a ValueError, as the numpy array is a different size that the dictionary keys/values.

AttributeError: 'numpy.ndarray' object has no attribute 'translate'

推荐答案

这样做会吗?有时,纯Python是处理此类问题的一种好方法.下面将构建翻译列表(轻松转换回numpy数组)和合并的输出.

Will this do? Sometimes, plain Python is a good, direct way to handle such things. The below builds a list of translations (easily converted back to a numpy array) and the joined output.

import numpy as np abc_array = np.array(['B', 'D', 'A', 'F', 'H', 'I', 'Z', 'J']) transdict = {'A': 'Adelaide', 'B': 'Bombay', 'C': 'Cologne', 'D': 'Dresden', 'E': 'Erlangen', 'F': 'Formosa', 'G': 'Gdansk', 'H': 'Hague', 'I': 'Inchon', 'J': 'Jakarta', 'Z': 'Zambia' } phoenetic = [transdict[letter] for letter in abc_array] print ' '.join(phoenetic)

输出为:

Bombay Dresden Adelaide Formosa Hague Inchon Zambia Jakarta

更多推荐

如何使用字典来翻译/替换数组的元素?

本文发布于:2023-11-26 03:11:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632402.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   如何使用   字典   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!