這是你的意思嗎?
In [3]: l1 = [[1,2,3],[4,5,6],[7,8,9,10],[11,12,13,14,15]]
In [4]: [e for l2 in l1 for e in l2 if e>5]
Out[4]: [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
爲了得到(內列出的)的指數,你可以使用enumerate
:
In [5]: [(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]
Out[5]:
[(2, 6),
(0, 7),
(1, 8),
(2, 9),
(3, 10),
(0, 11),
(1, 12),
(2, 13),
(3, 14),
(4, 15)]
如果你想在一個單獨的列表索引(UN)郵編:
In [6]: list(zip(*[(i2, e) for l2 in l1 for i2, e in enumerate(l2) if e>5]))
Out[6]: [(2, 0, 1, 2, 3, 0, 1, 2, 3, 4), (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)]
[如果您使用的是Python 2,則不需要撥打list
]。類似的方法會給你索引到兩個外部和內部列表:
In [7]: [((i1,i2), e) for (i1,l2) in enumerate(l1) for i2, e in enumerate(l2) if e>5]
Out[7]:
[((1, 2), 6),
((2, 0), 7),
((2, 1), 8),
((2, 2), 9),
((2, 3), 10),
((3, 0), 11),
((3, 1), 12),
((3, 2), 13),
((3, 3), 14),
((3, 4), 15)]
,或者解壓縮:
In [8]: idx, items = list(zip(*[((i1,i2), e) for (i1,l2) in enumerate(l1)
for i2, e in enumerate(l2) if e>5]))
In [8]: idx
Out[8]:
((1, 2),
(2, 0),
(2, 1),
(2, 2),
(2, 3),
(3, 0),
(3, 1),
(3, 2),
(3, 3),
(3, 4))
In [9]: items
Out[9]: (6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
正好!還有一種方法可以使這些指標達到這些值嗎? –
不錯,你可以添加第二個'enumerate()'來包含內部列表的索引,也許? – SiHa