Home > front end >  Creating a new list from another one and filling missing values by repeating
Creating a new list from another one and filling missing values by repeating

Time:04-25

I have two lists, one contains the working days, the other one contains the fees corresponding to the working days:

wd = [1, 4, 5, 6]
fees = [1.44, 1.17, 1.21, 1.26]

I need a third list with all workdays, filling up fees in the workdays that do not have fees with fees from the previous day:

result = [1.44, 1.44, 1.44, 1.17, 1.21, 1.26]
correspDay = [1, 2, 3, 4, 5, 6]

How can I code this?

CodePudding user response:

I'd start by building a dictionary to be able to look up fees by day:

>>> wd = [1,4,5,6]
>>> fees = [1.44, 1.17, 1.21, 1.26]
>>> fee_dict = dict(zip(wd, fees))

Then build correspDay with a simple range:

>>> correspDay = list(range(1, 7))

and build result by iterating over correspDay, using fee_dict to look up the fees and using the last entry when fee_dict comes up empty:

>>> result = []
>>> for i in correspDay:
...     result.append(fee_dict.get(i) or result[-1])
...
>>> result
[1.44, 1.44, 1.44, 1.17, 1.21, 1.26]

CodePudding user response:

I would put the values in a dictionary, then loop through the days of the week (1-7) checking if we already have a value for that day. If you do have a value for that day store it incase the next day doesn't have a value. If there isn't a value create an item in the dictionary with a key for that day and a value of the last fee.
At the end I have sorted the list but there is no real reason to do this other than to make the output easier to read

fees_dict = {1: 1.44, 4: 1.17, 5: 1.21, 6: 1.26}
last_fee = 0
for i in range(1, 8):
    if i in fees_dict:
        last_fee = fees_dict[i]
    else:
        fees_dict[i] = last_fee

sorted_fees_dict = dict(sorted(fees_dict.items()))
print(sorted_fees_dict)

CodePudding user response:

feeMap maps days to fee that has to be paid prev is used to store the previous value(fee).

#!/usr/bin/env python3.10

wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]

corresDay = list(range(1, 6))

feeMap = dict()
index = 0

for index, day in enumerate(wd):
    feeMap[day] = fees[index]

prev = None
for day in range(1, 6):
    if day not in feeMap.keys():
        feeMap[day] = prev
    else:
        prev = feeMap[day]
feeMap = sorted(feeMap.items())

print(feeMap)

output:

$ ./working_days.py 
[(1, 1.44), (2, 1.44), (3, 1.44), (4, 1.17), (5, 1.21), (6, 1.26)]

CodePudding user response:

I didn't do anything I saw the good people above and I try to make it more clear for you.

wd = [1,4,5,6]
fees = [1.44, 1.17, 1.21, 1.26]
fee_dict = dict(zip(wd, fees))
correspDay = list(range(1,8))
result = []
for i in correspDay:
    result.append(fee_dict.get(i) or result[-1])

I just add this line to make the output in dictionary

result = dict(zip(correspDay, result))

output:

{1: 1.44, 2: 1.44, 3: 1.44, 4: 1.17, 5: 1.21, 6: 1.26, 7: 1.26}
  • Related