0

我有以下格式的列表列表

a = [[1,...,255],[1,...,255],...,[1,...,255]]

即一个任意长度的列表,其中包含固定长度为 255 的整数列表。(固定长度列表的值是来自“现实世界”的数据,而不是本例中的整数 1 到 255。)

现在,我想过滤掉所有内部列表(长度为 255)中的所有值,0如果它们的值高于某个阈值,则将它们设置为。

有没有一种聪明的方法可以做到这一点而不必编写两个 for 循环?

4

3 回答 3

4

你可以numpy很容易地做到这一点:

import numpy as np

a = [range(255) for _ in range(10)]
np_a = np.array(a)    
# set all values above 200 to 0
np_a[np_a > 200] = 0
# np_a now contains the data with all values above 200 changed to 0

# if you needed to convert the numpy array back to a python list
a = np_a.tolist()

输出以显示它工作。

In [209]: np_a
Out[209]:
array([[  0,   1,   2, ..., 252, 253, 254],
       [  0,   1,   2, ..., 252, 253, 254],
       [  0,   1,   2, ..., 252, 253, 254],
       ...,
       [  0,   1,   2, ..., 252, 253, 254],
       [  0,   1,   2, ..., 252, 253, 254],
       [  0,   1,   2, ..., 252, 253, 254]])

In [210]: np_a[np_a > 252]  = 0

In [211]: np_a
Out[211]:
array([[  0,   1,   2, ..., 252,   0,   0],
       [  0,   1,   2, ..., 252,   0,   0],
       [  0,   1,   2, ..., 252,   0,   0],
       ...,
       [  0,   1,   2, ..., 252,   0,   0],
       [  0,   1,   2, ..., 252,   0,   0],
       [  0,   1,   2, ..., 252,   0,   0]])
于 2013-02-01T11:56:30.240 回答
0
# arbitarry length list of 255 length lists.    
l = [range(255)]*3 # 3 inner lists (as example)

# get filtered results:
f = [[k if k > 5 else 0 for k in j] for j in l] # filter at value 5 (as example)

# as a function:
def filter(lst, num):
    return [[k if k > num else 0 for k in j] for j in lst]

# as an iter over inner lists.
def filter(lst, num):
    for j in lst:
        yield [k if k > num else 0 for k in j]
于 2013-02-01T12:07:21.220 回答
0

变体 1:只有 1 for,例如:

dst = []
for s in src:
    dst.append([x if x < 3 else 0 for x in s])

变体 2:没有明确的for

filter = lambda lst: [x if x < 3 else 0 for x in lst]
dst = [filter(x) for x in src]
于 2013-02-01T11:57:51.993 回答