python 列表切片后如何保留其原索引,变换入其它列表呢?

python 列表切片后如何保留其原索引,变换入其它列表呢?

问题描述:

谢谢哦!

开始

 

import numpy as np
import time

采用numpy数组操作,避开循环

 

def get_index_from_array(from_array, purpose_array):
    purpose_array = np.array(purpose_array)
    from_array = np.array(from_array)
    purpose_idx_in_from = -np.ones(purpose_array.shape).astype(int)     #初始化待返回的索引数组为-1,长度对应purpose_array
    p_idx = np.in1d(purpose_array, from_array)      #筛选出 purpose_array 存在于 from_array 中存在的项
    union_array = np.hstack((from_array, purpose_array[p_idx]))         #合并from_array 和从 purpose_array 中筛选出来的数组
    _, union_idx, union_inv = np.unique(union_array, return_index=True, return_inverse=True)    #unique函数得到索引值
    purpose_idx_in_from[p_idx] = union_idx[union_inv[len(from_array):]] #待返回的索引数组赋值
    return purpose_idx_in_from

测试

 

purpose_array = np.array(['b', 't', 'd', 'g', 'f', 'f', 'g', 'b', 'g', 'f', 'p', 'd', 'f', 'r', 'g', 'w', 't', 'd', 'e', 'b', 'e'])
from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e'])
idx = get_index_from_array(from_array, purpose_array)
print(idx)
pos_idx = (idx != -1)
test_a = purpose_array[pos_idx]
test_b = from_array[idx[pos_idx]]
print((test_a == test_b).all())

unique函数

 

from_array = np.array(['e', 'c', 'f', 'a', 'e', 'g', 'f', 'a', 'b', 'd', 'd', 'e'])
test = np.unique(from_array, True, True, True)
print(test)

你这图片和切片有关系吗?

请说清楚,你希望通过什么数据,来得出什么数据?

 

a=['a','b','c','d','e']
b=['c','d','b','a','e','c']
c=[]

for i in range(len(b)):
	c.append(a.index(b[i]))   #在列表a中寻找b[i]项并将其索引(列表a)添加到列表c
print(c)

望采纳

a=['a','b','c','d','e']
b=['c','d','b','a','e','c', 'f']

c = [a.index(i) if i in a else -1 for i in b]
print(c)