查找大于 x 的元素的索引

新手上路,请多包涵

给定以下向量,

 a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

我需要确定元素大于等于 4 的“a”的索引,如下所示:

 idx = [3, 4, 5, 6, 7, 8]

“idx”中的信息将用于从另一个列表 X 中删除元素(X 具有与“a”相同数量的元素):

 del X[idx] #idx is used to delete these elements in X. But so far isn't working.

我听说 numpy 可能有帮助。有任何想法吗?谢谢!

原文由 Oliver Amundsen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 416
2 个回答

好的,我明白你的意思了,一行 Python 就足够了:

使用列表理解

[ 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 函数将返回一个元组列表

>>> zip(a,x)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]

列表理解是在“in”之后的列表上循环元素的快捷方式,并使用表达式评估元素,然后将结果返回到列表,您还可以添加要返回的结果的条件

>>> [expression(element) for **element** in **list** if condition ]

此代码只返回所有压缩的对。

 >>> [(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')]

我们所做的是通过指定“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')]

使用 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

在 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']

itertools.compress 的解释,我想这对你的理解会很清楚:

 >>> [ _ for _ in itertools.compress([1,2,3,4,5],[False,True,True,False,True]) ]
[2, 3, 5]

原文由 Shawn Zhang 发布,翻译遵循 CC BY-SA 3.0 许可协议

>>> [i for i,v in enumerate(a) if v > 4]
[4, 5, 6, 7, 8]

enumerate 返回数组中每个项目的索引和值。因此,如果值 v 大于 4 ,则在新数组中包含索引 i

或者您可以就地修改您的列表并排除上面的所有值 4

 >>> a[:] = [x for x in a if x<=4]
>>> a
[1, 2, 3, 4]

原文由 Aesthete 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题