Home > database >  how to fill the value 'None' if the main list value is not presented in sublist
how to fill the value 'None' if the main list value is not presented in sublist

Time:02-18

I am trying to create the new nested list from one main-list and different sub-lists. sub list values are presented in main list. I have a main list like this.All the sub-list values are unique values of main list.

mainlist = ['a', 'b', 'c', 'd', 'e']

sublist are like this.

sublista = ['a', 'b']
sublistb = ['c', 'd', 'e']
sublistc = ['b', 'e']
sublistd = ['c']

I want to get the final list like this.

combined_list = [['yes', 'yes', None, None, None],
                 [None, None, 'yes', 'yes', 'yes'],
                 [None, 'yes', None, None, 'yes'],
                 [None, None, 'yes', None, None]]

CodePudding user response:

You can use list comprehension combined with a conditional expression, like this:

mainlist = ['a', 'b', 'c', 'd', 'e']
sublista = ['a', 'b']

result = ["yes" if e in sublista else None for e in mainlist]
print(result)

But you need to decide how to handle those sublists, since holding each one as a separate variable is not manageable in the long run. Maybe combine them into a single list (of lists)?

  • Related