Search code examples
pythonlisttxt

Python - breaking down the percentage of values and adding new rows to the list


I'm a beginner in python and can't figure out the percentage breakdown of the amount. I would like the rows to contain lines with the calculated amounts.

DATA FROM TXT:

['Date', 'Period', 'NumberBill', 'Amount', 'KEY', 'WHAT\n']
['31.01.2022', '2', 'BILL3', '-1800.00', 'TEAM', 'BILL\n']
['03.02.2022', '2', 'BILL2', '644.00', 'PERSON','BILL\n']
['03.02.2022', '2', 'BILL1', '150.00', 'TEAM', 'BILL']

OUT_my:

['31.01.2022', '2', 'BILL3', '-1800.00', 'TEAM', 'BILL\n', -540.0, -360.0, -900.0]
['03.02.2022', '2', 'BILL1', '150.00','TEAM', 'BILL', 45.0, 30.0, 75.0]

I wrote:

filepath = "test.txt"
file = open(filepath, "r")
for i in file:
 iSplit = i.split(";")

 percentage1 = 0.30
 percentage2 = 0.20
 percentage3 = 0.50
 result1 = 0
 result2 = 0
 result3 = 0

 if iSplit[4] == 'TEAM':
     result1 = float(iSplit[3]) * percentage1
     result2 = float(iSplit[3]) * percentage2
     result3 = float(iSplit[3]) * percentage3
     iSplit.append(round(result1, 2))
     iSplit.append(round(result2, 2))
     iSplit.append(round(result3, 2))
     print(iSplit)`

What I want to get:

['03.02.2022', '2', 'BILL2', '644.00', 'PERSON','BILL]
['31.01.2022', '2', 'BILL3', '-540.00', 'TEAM', 'BILL]
['31.01.2022', '2', 'BILL3', '-360.00', 'TEAM', 'BILL]
['31.01.2022', '2', 'BILL3', '-900.00', 'TEAM', 'BILL]
['03.02.2022', '2', 'BILL1', '45.00', 'TEAM', 'BILL']
['03.02.2022', '2', 'BILL1', '30.00', 'TEAM', 'BILL']
['03.02.2022', '2', 'BILL1', '75.00', 'TEAM', 'BILL']

Solution

  • To get the result you want, you should print a new row for each percentage, with the amount replaced by the amount multiplied by the percentage, not append them all to the original row.

    And to get the non-team rows, use an else: block to print the original row.

    filepath = "test.txt"
    
    team_percentages = [0.30, 0.20, 0.50]
    
    with open(filepath, "r") as file:
        for i in file:
            iSplit = i.split(";")
    
            if iSplit[4] == 'TEAM':
                for percent in team_percentages:
                    new_row = isplit.copy()
                    new_row[3] = str(float(iSplit[3]) * percent)
                    print(new_row)
            else:
                print(iSplit)