Python 查找大于 x 的元素的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13717463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find the indices of elements greater than x
提问by Oliver Amundsen
Given the following vector,
给定以下向量,
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I need to identify the indices of "a" whose elements are >= than 4, like this:
我需要确定元素大于等于 4 的“a”的索引,如下所示:
idx = [3, 4, 5, 6, 7, 8]
The info in "idx" will be used to delete the elements from another list X (X has the same number of elements that "a"):
"idx" 中的信息将用于从另一个列表 X 中删除元素(X 具有与 "a" 相同数量的元素):
del X[idx] #idx is used to delete these elements in X. But so far isn't working.
I heard that numpy might help. Any ideas? Thanks!
我听说 numpy 可能会有所帮助。有任何想法吗?谢谢!
采纳答案by Shawn Zhang
OK, I understand what you mean and a Single line of Python will be enough:
好的,我明白你的意思,一行 Python 就足够了:
using list comprehension
使用列表理解
[ j for (i,j) in zip(a,x) if i >= 4 ]
# a will be the list compare to 4
# x another list with same length
Explanation:
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j']
Zip function will return a list of tuples
Zip 函数将返回一个元组列表
>>> zip(a,x)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
List comprehension is a shortcut to loop an element over list which after "in", and evaluate the element with expression, then return the result to a list, also you can add condition on which result you want to return
列表推导是在“in”之后的列表上循环元素的快捷方式,并使用表达式评估元素,然后将结果返回到列表,您也可以添加要返回的结果的条件
>>> [expression(element) for **element** in **list** if condition ]
This code does nothing but return all pairs that zipped up.
这段代码除了返回所有压缩的对之外什么都不做。
>>> [(i,j) for (i,j) in zip(a,x)]
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
What we do is to add a condition on it by specify "if" follow by a boolean expression
我们所做的是通过指定“if”后跟布尔表达式来为其添加条件
>>> [(i,j) for (i,j) in zip(a,x) if i >= 4]
[(4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
using Itertools
使用迭代工具
>>> [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ]
# a will be the list compare to 4
# d another list with same length
Use itertools.compress with single linein Python to finish close this task
在 Python 中使用单行itertools.compress完成关闭此任务
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j'] # another list with same length
>>> map(lambda x: x>=4, a) # this will return a boolean list
[False, False, False, True, True, True, True, True, True]
>>> import itertools
>>> itertools.compress(d, map(lambda x: x>4, a)) # magic here !
<itertools.compress object at 0xa1a764c> # compress will match pair from list a and the boolean list, if item in boolean list is true, then item in list a will be remain ,else will be dropped
#below single line is enough to solve your problem
>>> [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ] # iterate the result.
['d', 'e', 'f', 'g', 'h', 'j']
Explanation for itertools.compress, I think this will be clear for your understanding:
itertools.compress 的解释,我想这对你的理解会很清楚:
>>> [ _ for _ in itertools.compress([1,2,3,4,5],[False,True,True,False,True]) ]
[2, 3, 5]
回答by Aesthete
>>> [i for i,v in enumerate(a) if v > 4]
[4, 5, 6, 7, 8]
enumeratereturns the index and value of each item in an array. So if the value vis greater than 4, include the index iin the new array.
enumerate返回数组中每一项的索引和值。因此,如果该值v大于4,则i在新数组中包含索引。
Or you can just modify your list in place and exclude all values above 4.
或者您可以就地修改您的列表并排除上面的所有值4。
>>> a[:] = [x for x in a if x<=4]
>>> a
[1, 2, 3, 4]
回答by Joran Beasley
>>> import numpy as np
>>> a = np.array(range(1,10))
>>> indices = [i for i,v in enumerate(a >= 4) if v]
>>> indices
[3, 4, 5, 6, 7, 8]
>>> mask = a >= 4
>>> mask
array([False, False, False, True, True, True, True, True, True], dtype=boo
l)
>>> a[mask]
array([4, 5, 6, 7, 8, 9])
>>> np.setdiff1d(a,a[mask])
array([1, 2, 3])
回答by Shawn Zhang
using filter built-in function is fine
使用过滤器内置功能很好
>>>a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>filter(lambda x : x < 4, a)
[1, 2, 3]
Explanation
解释
filter(FUN, Iterable)
过滤器(有趣,可迭代)
this expression will iterate all element from Iterable and supply to FUN function as argument, if return is True ,then the arugment will be append to a internal list
此表达式将迭代 Iterable 中的所有元素并作为参数提供给 FUN 函数,如果 return 为 True ,则参数将附加到内部列表
lambda x: x > 4
λ x: x > 4
this means a anonymous function that will take a argument and test it if bigger than 4, and return True of False value
这意味着一个匿名函数将接受一个参数并测试它是否大于 4,并返回 True 或 False 值
Your solution
您的解决方案
if you are try to delete all elements larger than 4 ,then try blow
如果您尝试删除所有大于 4 的元素,请尝试删除
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> filter(lambda x: x<4 ,a)
[1, 2, 3]
回答by Okapi575
The simplest in my eyes would be to use numpy
在我看来最简单的就是使用 numpy
X[np.array(a)>4]#X needs to be np.array as well
Explanation: np.array converts a to an array.
说明: np.array 将 a 转换为数组。
np.array(a)>4 gives a bool array with all the elements that should be kept
np.array(a)>4 给出了一个包含所有应该保留的元素的 bool 数组
And X is filtered by the bool array so only the elements where a is greater than 4 are selected (and the rest discarded)
并且 X 被 bool 数组过滤,因此只选择 a 大于 4 的元素(其余的被丢弃)
回答by singrium
I guess I came here a bit late (while things got easier using Numpy)..
我想我来得有点晚了(虽然使用 Numpy 事情变得更容易了)..
import numpy as np
# Create your array
a = np.arange(1, 10)
# a = array([1, 2, 3, 4, 5, 6, 7, 8, 9])
# Get the indexes/indices of elements greater than 4
idx = np.where(a > 4)[0]
# idx = array([4, 5, 6, 7, 8])
# Get the elements of the array that are greater than 4
elts = a[a > 4]
# elts = array([5, 6, 7, 8, 9])
# Convert idx(or elts) to a list
idx = list(idx)
#idx = [4, 5, 6, 7, 8]

