1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| import copy import heapq import numpy as np
def getListMinNumIndex(nums: list, k: int): min_num_index = list(map(nums.index, heapq.nsmallest(k, nums))) print('min_num_index:', min_num_index)
def getListMinNumIndex2(nums: list, k: int): copy_nums = copy.deepcopy(nums) copy_nums.sort() min_num_index = [nums.index(one) for one in copy_nums[:k]] print('min_num_index:', min_num_index)
def getListMinNumIndex3(nums: list, k: int): num_dict = {} for i in range(len(nums)): num_dict[i] = nums[i] sort_list = sorted(num_dict.items(), key=lambda x: (x[1], -x[0])) min_num_index = [item[0] for item in sort_list[:k]] print('min_num_index:', min_num_index)
def getListMinNumIndex4(nums: list, k: int): copy_list = copy.deepcopy(nums) max_num = float('inf') min_num_index = [] for i in range(k): one_min_index = copy_list.index(min(copy_list)) min_num_index.append(one_min_index) copy_list[one_min_index] = max_num print('min_num_index:', min_num_index)
def getListMinNumIndex5(nums: list, k: int): nums = np.array(nums) print(nums.argsort()) min_num_index = nums.argsort()[:k] print('min_num_index:', min_num_index)
if __name__ == '__main__': nums = [12, 3, 4, 18, 20, 1, 34, 2, 0] k = 3 getListMinNumIndex(nums, k) getListMinNumIndex2(nums, k) getListMinNumIndex3(nums, k) getListMinNumIndex4(nums, k) getListMinNumIndex5(nums, k)
|