Reputation: 1
I am trying to add elements from one list to another list that has part of the elements but some are missing
days_m = ['1','2','3']
dates = ['4-','10-','10-20','10-4','9-']
start_end = []
for f,b in itertools.zip_longest(dates, days_m, fillvalue = 'NA'):
if len(f) < 4:
date = f+b
start_end.append(date)
elif len(f) >= 4:
start_end.append(date)
I expect the output to be
['4-1', '10-2', '10-20', '10-4', '9-3']
But the actual output has been
['4-1', '10-2', '10-2', '10-2', '9-NA']
Upvotes: 0
Views: 97
Reputation: 140196
First, you cannot use zip_longest
here. Because you mean to pick a value from the second list only if the length is < 4. zip_longest
does that all the time.
Then, you're not updating date
in the second branch.
I suggest to use iter
on days_m
, and iterate on it manually with next
, with the default value of "NA"
. Also drop the double length test as it is redundant.
And always use an updated version of f
. Just concatenate to it when needed, else use as-is.
days_m = iter(['1','2','3'])
dates = ['4-','10-','10-20','10-4','9-']
start_end = []
for f in dates:
if len(f) < 4:
f += next(days_m,"NA")
start_end.append(f)
print(start_end)
result:
['4-1', '10-2', '10-20', '10-4', '9-3']
Upvotes: 1