2

I have an array like this: ['a', ['e', 'r', 't'], 'c'].

I want to use some sort of processing to make the array neat: [['a', 'e', 'c'], ['a', 'r', 'c'], ['a', 't', 'c']].

If the array is: ['a', ['e', 'r', 't'], ['c', 'd']].

The result is: [['a', 'e', 'c'], ['a', 'e', 'd'], ['a', 'r', 'c'], ['a', 'r', 'd'], ['a', 't', 'c'], ['a', 't', 'd']].

And the length of the array is not fixed to 3, other examples:

['a', 'b'] = > ['a', 'b']
['a', ['b', 'c']] => [['a', 'b'], ['a', 'c']]
['ab', ['b', 'c']] => [['ab', 'b'], ['ab', 'c']]
[[1, 2], 3, 4] => [[1, 3, 4], [2, 3, 4]]

So what should I do? Is there a solution in Numpy?

7
  • 5
    What's the expected output for - ['a', ['e', 'r', 't'], ['b', 'c']]? Commented Jul 6, 2018 at 7:09
  • 2
    Is the depth consistent ? What about ['a', ['e', 'r', ['t', 'y']], 'c'] Commented Jul 6, 2018 at 7:14
  • did you mean that you want to convert some elements to a list and add to them things later? Commented Jul 6, 2018 at 7:18
  • Thanks, I modified my question, the highest depth is 2.@Divakar @Bck Commented Jul 6, 2018 at 7:24
  • Can you explain how you arrived at the expected output? Commented Jul 6, 2018 at 7:25

2 Answers 2

3

Unless I misunderstand the question, you just want the product of the sub-lists, although you have to wrap any single elements into lists first.

>>> 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')]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I think this is neat way to do it.
0

I have a recursive solution:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.