我想重新定义并列出int64的数组,这样数组中的值就会被排序,并且只包含非False的值



我有以下数据:

data = ['10 20 10 36 30 33 400 400 -1 -1', 
'100 50 50 30 60 27 70 24 -2 -2 700 700', 
'300 1000 80 21 90 18 100 15 110 12 120 9 900 900 -3 -3',
'30 90 130 6 140 3 -4 -4 1000 1000']
data = [e.split() for e in l]
concentration = [np.array(concentration[3::2], dtype=np.int) for concentration in data]

我想将变量(浓度(中不在区间(0-50(内的值设置为False/0。所以我做了以下代码:

for row in range(len(concentration)):
for element in range(len(concentration[row])):
if 0 > concentration[row][element] or concentration[row][element] > 50:
concentration[row][element] = False
print("Error: Index {:} in time is out of range".format(element))

我得到以下输出,我的浓度变量如下所示:

Array of int64 [36 33 0 0]
Array of int64 [30 27 24 0 0]
Array of int64 [21 18 15 12 0 0]
Array of int64 [6 3 0 0]

现在我想重新定义我的变量(concentration(,其中的值是排序的,并且只包含True/1值(不是False/0的值(。我希望我的新浓度变量看起来像这样:

Array of int64 [33 36]
Array of int64 [24 27 30]
Array of int64 [12 15 18 21]
Array of int64 [3 6]

感谢到目前为止的帮助!

您可以使用以下方式解决问题:

initial_data = ['10 20 10 36 30 33 400 400 -1 -1', 
'100 50 50 30 60 27 70 24 -2 -2 700 700', 
'300 1000 80 21 90 18 100 15 110 12 120 9 900 900 -3 -3',
'30 90 130 6 140 3 -4 -4 1000 1000']
result = [sorted(filter(lambda x: 0 < x < 50, 
list(map(int, elem.split()))[3::2])) for elem in initial_data]
print(result)
# [[33, 36], [24, 27, 30], [9, 12, 15, 18, 21], [3, 6]]

如果你需要numpy数组而不是列表,你可以在列表理解中添加转换:

result = [np.array(sorted(filter(lambda x: 0 < x < 50, 
list(map(int, elem.split()))[3::2])), dtype=np.int) 
for elem in initial_data]
print(result)
# [array([33, 36]), array([24, 27, 30]), array([ 9, 12, 15, 18, 21]), array([3, 6])]

更新

为了重新定义你的浓度变量,你可以使用以下结构:

concentration = list(map(lambda x: np.sort(x[x > 0]), concentration))

最新更新