假设我有一个矩阵:
a = [[4,7,2],[0,1,4],[4,5,6]]
我想得到
b = [0, 1]
c = [[2],[0,1]]
b = [0,1]
是因为a
和0
位置的1
的内部列表包含的值小于3
。 c = [[2],[0,1]]
是因为[2]
中第一个子列表的b
nd元素低于3,而[0,1]
是因为{{1 }}低于3。我尝试过:
b
它仅返回原始矩阵。
如何在python中获得for i in a:
for o in i:
if o < 3:
print(i)
&b
?
答案 0 :(得分:0)
您可以利用enumerate(iterable[,startingvalue])
来获得索引和所迭代对象的值:
a = [[4,7,2],[0,1,4],[4,5,6]]
thresh = 3
b = [] # collects indexes of inner lists with values smaller then thresh
c = [] # collects indexes in the inner lists that are smaller then thresh
for idx, inner_list in enumerate(a):
if any(value < thresh for value in inner_list):
b.append(idx)
c.append([])
for idx_2, value in enumerate(inner_list):
if value < thresh:
c[-1].append(idx_2)
print(a)
print(b)
print(c)
输出:
[[4, 7, 2], [0, 1, 4], [4, 5, 6]]
[0, 1]
[[2], [0, 1]]
Doku: