以智能方式过滤列表列表

时间:2013-02-01 11:50:31

标签: python

我有以下格式的列表列表

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

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

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

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

3 个答案:

答案 0 :(得分: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]])

答案 1 :(得分: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]

答案 2 :(得分: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]