0

Lets say I have this structure

[[[1,2],[3,4]],[[8,9],[7,7]]] 

I want to iterate the list and have this result:

[[3,2],[8,7]] 

This is would be reducing the list list of arrays in the first level [[1,2],[3,4]] to one single array where the maximum selected for the first element and the minimum is found for the second.

I have already done it manually, just iterating the groups, iterating again, storing the first value and seeing if the next is bigger or smaller, I store it in a list and create another list.

I would like to find a more elegant method with list comprehensions and so on, I'm pretty sure I can use zip here to group the values in the same group but I haven't been successful so far.

2 Answers 2

1

You can use zip, and by unpacking the result into individual values it is pretty easy to do what you are looking for, e.g.:

>>> x = [[[1,2],[3,4]],[[8,9],[7,7]]] >>> [[max(a), min(b)] for k in x for a, b in [zip(*k)]] [[3, 2], [8, 7]] 

An alternative way without unpacking is to have a cycling function iterable (max, min, max, min, ...) and use nested list comprehensions, e.g.:

>>> import itertools as it >>> maxmin = it.cycle([max, min]) >>> [[next(maxmin)(a) for a in zip(*k)] for k in x] [[3, 2], [8, 7]] 

Or index into a list of functions:

>>> import itertools as it >>> maxmin = [max, min] >>> [[maxmin[i](a) for i, a in enumerate(zip(*k))] for k in x] [[3, 2], [8, 7]] 
Sign up to request clarification or add additional context in comments.

4 Comments

I don't necessarily want to use zip, it was just what I though might help. I'll see how this applies, the lists are actually of four elements.
The comment was for the previous answer before the edit, I'll check this one.
What do you mean 4 elements, can you give a more complete example? This doesn't care how many pairs you have or how many groups of pairs you have but will not work if you have more than pairs though it is easy to extend - a, b, c, d
This seems to work exactly as I need, disregard the first comment, I'm just giving it a try.
1

This will work without zip:

mylist = [[[1,2],[3,4]],[[8,9],[7,7]]] [[max(y[0] for y in x), min(y[1] for y in x)] for x in mylist] 

The main disadvantage of this is that it looks through each sub-list twice, once to find the maximum (of the first items) and once to find the minimum (of the second items).

1 Comment

Oh nice, this seems pretty much what I need, the only problem is that I have four, so I would have to iterate four times each... but I don;t think it's that performance dependent. I'll give it a go.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.