如何在Python中使锯齿状数组整洁?

时间:2018-07-06 07:09:04

标签: python python-3.x numpy

我有一个像这样的数组:<?php require_once("config.php"); $query = "SELECT name, fname, notes FROM lab_examinations"; $stmt = $db->prepare($query); $stmt->execute(); $result = array('data' => array()); while($row = $stmt->fetch(PDO:: FETCH_OBJ) ) { $name = $row->name; $fname = $row->fname; $notes = $row->notes; $result['data'][] = array($name, $fname, $notes); } echo json_encode($result);

我想使用某种处理方法使数组整洁: ['a', ['e', 'r', 't'], 'c']

如果数组为:[['a', 'e', 'c'], ['a', 'r', 'c'], ['a', 't', 'c']]

结果是: ['a', ['e', 'r', 't'], ['c', 'd']]

并且数组的长度不固定为3,其他示例:

[['a', 'e', 'c'], ['a', 'e', 'd'], ['a', 'r', 'c'], ['a', 'r', 'd'], ['a', 't', 'c'], ['a', 't', 'd']]

那我该怎么办? Numpy中有解决方案吗?

2 个答案:

答案 0 :(得分:3)

除非我必须误解这个问题,否则您只想要子列表的product,尽管您必须先将任何单个元素包装到列表中。

>>> from itertools import product
>>> arr = ['a', ['e', 'r', 't'], ['c', 'd']]
>>> listified = [x if isinstance(x, list) else [x] for x in arr]
>>> listified
[['a'], ['e', 'r', 't'], ['c', 'd']]
>>> list(product(*listified))
[('a', 'e', 'c'),
 ('a', 'e', 'd'),
 ('a', 'r', 'c'),
 ('a', 'r', 'd'),
 ('a', 't', 'c'),
 ('a', 't', 'd')]

答案 1 :(得分:0)

我有一个递归解决方案:

inlist1 = ['ab', ['e', 'r', 't'], ['c', 'd']]
inlist2 = [['a', 'b'], ['e', 'r', 't'], ['c', 'd']]
inlist3 = [['a', 'b'], 'e', ['c', 'd']]


def jagged(inlist):
    a = [None] * len(inlist)

    def _jagged(index):
        if index == 0:
            print(a)
            return
        v = inlist[index - 1]
        if isinstance(v, list):
            for i in v:
                a[index - 1] = i
                _jagged(index - 1, )
        else:
            a[index - 1] = v
            _jagged(index - 1)

    _jagged(len(inlist))


jagged(inlist3)