user3552459
user3552459

Reputation: 57

combining list of list with addition of value when list items are missing

I need to combine list of lists and add items when items are not present in other lists.

I need a way to represent when a value is not present in a list across three list of lists. In the example below ['e','f'] is only in list one (l1), so a placeholder would be added to list two (l2) and three (l3) to represent that it is in list one, but not list two and three. The placeholder would be something like ['e','-'].

l1 = [['a', 'b'],['e','f']]
l2 = [['a', 'b'],['c', 'd']]
l3 = [['a', 'b'],['c', 'd']]

So in the end, every list would have an entry for any list item that had a unique value in the first position of a list item.

l1 = [['a', 'b'],['c','-'],['e','f']
l2 = [['a', 'b'],['c','d'],['e','-']
l3 = [['a', 'b'],['c','d'],['e','-']

I tried converting the list of lists to sets and could find common objects, for example

l1_set = set(tuple(row) for row in l1)
l2_set = set(tuple(row) for row in l2)
l3_set = set(tuple(row) for row in l3)

print (ipl_set & vgda_set & odm_set)

set([('a', 'b')])

I am not sure how to manage the sets so I can find different values and modify the lists to include those different values, while keeping position in the list.

The order does matter. I don't want to simply append missing list items like this:

l1 = [['a', 'b'],['e','f'],['c','-']
l2 = [['a', 'b'],['c','d'],['e','-']
l3 = [['a', 'b'],['c','d'],['e','-']

Upvotes: 0

Views: 80

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195478

The function add_missing_items() accepts any number (>0) of lists and add to them items that are missing from other lists. Assumes that items inside the lists can be sorted alphabetically:

l1 = [['a', 'b'],['e','f']]
l2 = [['a', 'b'],['c', 'd']]
l3 = [['a', 'b'],['c', 'd']]

def add_missing_items(*lists):
    l_sets = [set(tuple(row) for row in l) for l in lists]
    u = l_sets[0].union(*l_sets[1:])

    for lst, slst in zip(lists, l_sets):
        l = [list(v) for v in u.difference(slst)]
        for missing_value in l:
            missing_value[1::1] = '-' * (len(missing_value)-1)
        lst[:] = sorted(lst + l)

add_missing_items(l1, l2, l3)

print(l1)
print(l2)
print(l3)

Prints:

[['a', 'b'], ['c', '-'], ['e', 'f']]
[['a', 'b'], ['c', 'd'], ['e', '-']]
[['a', 'b'], ['c', 'd'], ['e', '-']]

Upvotes: 1

damdamo
damdamo

Reputation: 353

You can test if a couple in a list is in another list like this:

l1 = [['a', 'b'],['e','f']]
l2 = [['a', 'b'],['c', 'd']]
l3 = [['a', 'b'],['c', 'd']]

for couple in l1:
    if couple not in l2:
        print(couple)

In the case above, it's just an example to show how you can find elements that are different from l1. However, you can image modify an array instead of just make a print.

Hence, if you want to modify your arrays, I advise you to copy them and not modify directly original arrays.

Upvotes: 0

Related Questions