[英]Calling function on each of numpy array elements and override its value in Python
I have a list: 我有一个清单:
letters = ('1', '2', '3', '5', '8', '13', '21')
Having number 8
, I can get it's index in letters as: letters.index('8')
有了数字
8
,我可以得到它的字母索引为: letters.index('8')
No, I have an array which contains only numbers that are in letters. 不,我有一个仅包含字母数字的数组。
numbers = [3, 8, 13, 21, 5]
How do I call index (or similar) function on each element? 如何在每个元素上调用索引(或类似)函数?
what I want to get is [2, 4, 5, 6, 3]
我想得到的是
[2, 4, 5, 6, 3]
Is there such function as index that can grab array instead on single element? 是否有诸如索引之类的功能可以代替单个元素上的数组? If that is required letters can be changed to array
如果需要,可以将字母更改为数组
You can try 你可以试试
letters = ('1', '2', '3', '5', '8', '13', '21')
numbers = [3, 8, 13, 21, 5]
result = [letters.index(str(n)) for n in numbers]
But this works only if all requests are present in letters
但这仅在所有请求均以
letters
形式出现时有效
You can try this to test if the request in letters
您可以尝试使用此方法来测试请求中是否包含
letters
[letters.index(str(n)) if str(n) in letters else -1 for n in numbers]
In case request in not letters
, you will have a -1
. 万一要求不以
letters
,您将得到-1
。 Beware that -1
is here to indicate that request is not present. 请注意,此处为
-1
表示不存在该请求。 letters[-1]
returns the last element of the tuple. letters[-1]
返回元组的最后一个元素。
I like to use map
functions - this is a great problem to apply a new technique. 我喜欢使用
map
功能-应用新技术是一个很大的问题。
def get_index(letters, element):
return letters.index(str(element))
indices_of_numbers = list(map(get_index, numbers))
we could wrap this in a function so we can remove the letters
argument from get_index
. 我们可以将其包装在一个函数中,以便可以从
get_index
删除letters
参数。
def get_indices_of_numbers(letters, numbers):
def get_index(element):
return letters.index(str(element))
indices_of_numbers = list(map(get_index, numbers))
return indices_of_numbers
You could convert letters
to int array and then use np.searchsorted
- 您可以将
letters
转换为int数组,然后使用np.searchsorted
np.asarray(letters,dtype=int).searchsorted(numbers)
Sample run - 样品运行-
In [42]: letters = ('1', '2', '3', '5', '8', '13', '21')
In [43]: numbers = [3, 8, 13, 21, 5]
In [44]: np.asarray(letters,dtype=int).searchsorted(numbers)
Out[44]: array([2, 4, 5, 6, 3])
If letters
is such that the int array version is not sorted, we need to feed in the additional argument sorter
with searchsorted
. 如果
letters
不能对int数组版本进行排序,则需要使用searchsorted
输入其他参数sorter
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.