Compute the Indices of the Target Element in Array/List using Py
- 时间:2020-09-13 14:33:25
- 分类:网络文摘
- 阅读:148 次
Given an array (or list), and a target element, find all the indices that the element appears in it. For example,
Array: [1, 2, 3, 4, 5, 5, 6, 7, 8], and find the element 5, which appears in index 4 and 5, thus return [4, 5].
This is a trivial question and most programmers know how to do this using a for loop. For example,
In Python:
1 2 3 4 5 6 | def getIndices(data, element): x = [] for i in range(len(data)): if data[i] == element: x.append(i) return x |
def getIndices(data, element):
x = []
for i in range(len(data)):
if data[i] == element:
x.append(i)
return xOr similarly in Javascript:
1 2 3 4 5 6 7 8 9 | function getIndices(data, element) { let x = []; for (let i = 0; i < data.length; i += 1) { if (data[i] === element) { x.push(i); } } return x; } |
function getIndices(data, element) {
let x = [];
for (let i = 0; i < data.length; i += 1) {
if (data[i] === element) {
x.push(i);
}
}
return x;
}However, as a spirit of avoiding loops as much as you can, we can simplify the implementation. In Python, we can use the enumerate and the list comprehension which gives us the following short and concise solution to return the list of the indices for a target element in the array.
1 2 | def getIndices(data, element): return [x for x, y in enumerate(data) if y == element] |
def getIndices(data, element):
return [x for x, y in enumerate(data) if y == element]In Javascript, we could similarly implement a enumerate function, alternatively, we can chain map and filter function.
1 2 3 4 5 6 7 8 | function getIndices(data, element) { let i = -1; return data.map(x => { i ++; // incrementing the index // return index for target element return x == element ? i : false; }).filter(x => typeof x !== 'boolean'); } |
function getIndices(data, element) {
let i = -1;
return data.map(x => {
i ++; // incrementing the index
// return index for target element
return x == element ? i : false;
}).filter(x => typeof x !== 'boolean');
}The map function maps those target elements with their indices, and others similar set to false – which will be filtered out via filter.
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:数学题:用一根20米长的铁丝,围成一个长、宽是整米数的长方形 数学题:有一杯糖水,糖与水的重量比是1:20 奥数题:如果甲先做1小时,然后乙接替甲做1小时 数学题:服装厂的工人每人每天可以生产4件上或7条裤子 数学题:一个长方体长,宽,高都是两位数,并且它们的和是偶数 数学题:若115,200,268被大于1的自然数除 数学题:一只蚂蚁从墙根竖直向上爬到墙头用了4分钟 一位农妇上午挎了一个空篮子笑眯眯地回家 奥数题:秋游时,小红小玲小芳三个好朋友在一个小组一起活动 平年和闰年自测题
- 评论列表
-
- 添加评论