从现有列表创建新数组

问题描述 投票:1回答:2

我有一个给定的数组,我想从第一个值开始获取每个第三个值,并将其附加到新列表中。我可以取所需的值,但它将作为1 x 28数组返回。我希望它以4 x 7数组形式返回。我如何知道到达第一行的末尾以开始新行?

代码:

import numpy as np

list = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
]
newlist = []
list = np.array(list)
for row in list:
    k = 0
    for value in row:
        if k % 3 == 0:
            newlist.append(value)
        else:
            pass
        k += 1
newlist = np.array(newlist)
print(newlist)

输出:

[ 1  4  7 10 13 16 19  2  5  8 11 14 17 20  3  6  9 12 15 18 21  4  7 10 13 16 19 22]

所需的输出:

[[ 1  4  7 10 13 16 19 ][ 2  5  8 11 14 17 20 ][ 3  6  9 12 15 18 21 ][ 4  7 10 13 16 19 22]]
python arrays list numpy append
2个回答
1
投票

尝试使用具有列表理解的::3切片:

l = [
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
    [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
    [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
]
print(np.array([i[::3] for i in l]))

要了解更多有关切片的信息,请看这里:

Understanding slice notation


0
投票

以另一种方式,将其全部制成一个数组,然后将其切片:

np.array(lst)[:,::3]

一点基准:

>>> timeit(lambda: np.array([i[::3] for i in lst]))
6.054426699999993
>>> timeit(lambda: np.array(lst)[:,::3])
9.345163799999995

并且请不要调用变量list或其他现有名称。

© www.soinside.com 2019 - 2024. All rights reserved.