Home > Mobile >  Combining two lists which contain strings and None type data
Combining two lists which contain strings and None type data

Time:08-15

I have two lists of data of the following form:

List1 = ['String1', None, None]
List2 = [None, 'String2', None]

I want to combine these lists to give the following:

List3 = ['String1', 'String2', None]

The current code I have is as follows based on other stack overflow questions:

''.join(filter(None, (df.iloc[0,:], df.iloc[1,:])))

CodePudding user response:

They're just lists and not dataframes, so toss out the current code. You can get List3 as follows:

List3 = [(x if type(x) == str else List2[i]) for i,x in enumerate(List1)]

Then each element of List3 will be the element at the same index of List1 if that element is a string, and the corresponding element of List2 otherwise.

CodePudding user response:

You can do it like this:

[e1 or e2 for e1,e2 in zip(List1, List2)]

CodePudding user response:

Since None works well with logical operators, you could also try this:

List3 = list(map(lambda x, y: x or y, List1, List2))

CodePudding user response:

There is no need to check for type. Use the fact that None evaluates to False in a boolean context.

List1 = ['String1', None, None]
List2 = [None, 'String2', None]

List3 = [List1[i] or List2[i] for i in range(len(List1))]
print(List3)
# ['String1', 'String2', None]
  • Related