Datadev
Datadev

Reputation: 71

consolidate multiple python list based on list values into one

I want to consolidate python lists based on values of list.

    [4, None, None]
    [None, 4.1, None]
    [None, None, 4.2]
    [4.1,4.2,4.3]
    [None,4.1,4.3]

to

[4,4.1,4.2,4.1,4.1]

I want to get result with list priority, If first list is not having value, then it check for second and then third.

Upvotes: 1

Views: 83

Answers (3)

Mark
Mark

Reputation: 92461

You can do this with a list comprehension and a condition:

ls = [
    [4,None,None],
    [None,4.1,None],
    [None,None,4.2]
]

[n for l in ls for n in l if n is not None]
# [4, 4.1, 4.2]

Edit based on new info

You can use the formulation next(generator expression) with a condition to get the first value from a sublist meeting your condition. For example:

ls = [
    [4,None,None],
    [None,4.1,None],
    [None,None,4.2],
    [4.1,4.2,4.3],
    [None,4.1,4.3]
]

[next(n for n in l if n is not None) for  l in ls]
# [4, 4.1, 4.2, 4.1, 4.1]

This will raise an exception if there is no good value in a sublist. You can pass a default value to next as a second argument if that's a possibility.

Upvotes: 4

AverageJoe9000
AverageJoe9000

Reputation: 338

Not sure what is your input, but based on your description I guess it is list of lists.

The easiest way is to do it is to loop over each element and check if element in list is null or not and add it to separate list.

Something like this:

result = []
for (list in lists):
  for (element in list): 
    if (element is not None):
       result.append(element)

print(result)

Upvotes: 0

David
David

Reputation: 1216

def consolidate_list(*lists):
    ans = [None] * max([len(lst) for lst in lists])
    for lst in lists:
        for i in range(len(lst)):
            if lst[i] is not None:
                ans[i] = lst[i]
    return ans


print(consolidate_list([4, None, None], [None, 4.1, None], [None, None, 4.2]))
# [4, 4.1, 4.2]

I think this is what you're looking for.

Upvotes: 0

Related Questions