如何从Python列表中提取同时还要考虑提取元素的位置?

Pyd*_*man 2 python indexing list python-2.7

给出一个list x例如

[4,6,7,21,1,7,3]
Run Code Online (Sandbox Code Playgroud)

我需要提取那些值less than or equal to 4.这很容易做到,但我还需要注意列表中这些值发生的位置.如果所有值都是唯一的,我知道我可能会list.index()以某种方式使用它.但是会有重复的价值观.如何最好地实现这一目标?

the*_*orn 5

怎么样简单

[(i, val) for i, val in enumerate([[4,6,7,21,1,7,3]) if val <= 4]
Run Code Online (Sandbox Code Playgroud)

或者根据你的用例,也许字典会更合适?从索引到值:

{i:val for i, val in enumerate([4,6,7,21,1,7,3]) if val <= 4}
Run Code Online (Sandbox Code Playgroud)

或从价值到指数:

from collections import defaultdict

indexes = defaultdict(list)
for i, val in enumerate([4,6,7,21,1,7,3]):
    if val <= 4:
        indexes[val].append(i)
Run Code Online (Sandbox Code Playgroud)