选择如何展宽数组(python)

时间:2019-11-25 12:03:02

标签: python numpy

这是我正在处理的数组的示例:

    records = [[[['   1'], ['   2'], ['   3'], ['   4']]], [[['   red'], ['   blue'], ['   black'], ['   white']]]]

我想以这样的结构结尾:

    [['   1','   2','   3','   4'],['   red','   blue','   black','   white']]

我尝试了以下操作:

    levelOne = [recs for sublist in records for recs in sublist]
    final = [recs for sublist in levelOne for recs in sublist]

我得到的是:

    [['   1'], ['   2'], ['   3'], ['   4'], ['   red'], ['  blue'], ['   black'], ['   white']]

3 个答案:

答案 0 :(得分:1)

使用内置的itertools.chain.from_iterable进行展平/链接。然后,只需将其应用于正确的嵌套列表级别即可:

import itertools
list(list(itertools.chain.from_iterable(rec[0])) for rec in records)

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

或作为单个列表理解

[[r[0] for r in rec[0]] for rec in records]

[['   1', '   2', '   3', '   4'],
 ['   red', '   blue', '   black', '   white']]

或者,如果嵌套列表以numpy数组开头,则可以使用numpy.reshape

np.reshape(np.array(records), (2, 4))

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')

答案 1 :(得分:1)

如果您的记录数组是numpy数组,则删除np.array(records)仅放置记录。如果您想要简单的列表,则删除np.array(list(...))中的np.array强制转换 在res中

import numpy as np
res=np.array(list(map(lambda x : x.reshape(-1), np.array(records))))

答案 2 :(得分:1)

您可以使用方法reshape

records = np.array(records)
records = records.reshape(2, -1)

print(records)

输出:

array([['   1', '   2', '   3', '   4'],
       ['   red', '   blue', '   black', '   white']], dtype='<U8')