好的,我理解了你的意思,一行Python代码就足够了:
使用列表推导式
[ j for (i,j) in zip(a,x) if i >= 4 ]
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']
>>> map(lambda x: x>=4, a)
[False, False, False, True, True, True, True, True, True]
>>> import itertools
>>> itertools.compress(d, map(lambda x: x>4, a))
<itertools.compress object at 0xa1a764c>
>>> [ _ for _ in itertools.compress(d, map(lambda x: x>=4,a)) ]
['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]
idx
示例是错误的,该列表中只有9个元素,因此只有9个索引,0-8。 - Aestheteidx
是元素列表,而你正在询问索引列表)。另外,请告诉我们在提问前你自己尝试了什么? - 0xc0de