OK,我明白你的意思和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(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')]
我们做的是它通过添加一个条件指定 “如果” 使用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
使用itertools.compress与布尔表达式
>>> [(i,j) for (i,j) in zip(a,x) if i >= 4]
[(4, 'd'), (5, 'e'), (6, 'f'), (7, 'g'), (8, 'h'), (9, 'j')]
跟随Python中单行完成关闭此任务
>>> 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的解释。压缩,我认为这将是清楚的理解:
>>> [ _ for _ in itertools.compress([1,2,3,4,5],[False,True,True,False,True]) ]
[2, 3, 5]
循环是一个很好的开始。 – monkut
您的'idx'示例是错误的,列表中只有** 9个元素**,因此** 9个索引0-8 **。 – Aesthete
你的问题与自己有点矛盾。看起来你可能会混淆索引与元素(你的'idx'实际上是元素列表,而你正在询问索引列表)。也请告诉你之前你自己尝试了什么? – 0xc0de