Home > Net >  How to update contents of one list with contents from another
How to update contents of one list with contents from another

Time:08-29

I have 2 lists. One containing a current stock portfolio ex. (['XYZ', '1029'], ['ABC', '132'], ...)

and another containing recently made trades ex. ['Buy', 'XYZ', '109'], ['Sell, 'ABC', '90'], ...

I need to update the contents of the first list depending on the action and stock symbol of the second list. I am not allowed to use dictionaries.

here is what I have so far

enter image description here

CodePudding user response:

You can do something like that:

portfolio = ['XYZ', '1029'], ['ABC', '132']
deals = [['Buy', 'XYZ', '109'], ['Sell', 'ABC', '90']]

portfolio_map = {}
for element in portfolio:
    portfolio_map[element[0]] = int(element[1])

for deal in deals:
    current_value = portfolio_map.setdefault(deal[1], 0)
    if deal[0] == 'Buy':
        portfolio_map[deal[1]]  = int(deal[2])
    elif deal[0] == 'Sell':
        portfolio_map[deal[1]] -= int(deal[2])

In the end, you have portfolio_map dict with all the updated portfolio.

CodePudding user response:

First, convert your list stock list to a dictionary.

stock_list = (['XYZ', '1029'], ['ABC', '132'], ...)
stock_dic = { key:value for (key,value) stock_list }

After that, iterate through the next list and apply the updates like so:

updates = ( ['Buy', 'XYZ', '109'], ['Sell, 'ABC', '90'], ... )
for state , key , val in updates:
    if state == 'Sell':
        stock_dic[key] -= val
    elif state == 'Buy' :
        stock_dic[key]  = val

Generally, dealing with a list in these scenarios is overall a bad practice as it drastically reduces the readability of your code.
Using a dictionary on the other hand simplifies the code a lot.

CodePudding user response:

If you are not allowed to use dicts, the only option, perhaps, is to do it iteratively:

portfolio = [['XYZ', '1029'], ['ABC', '132']]
deals = [['Buy', 'XYZ', '109'], ['Sell', 'ABC', '90']]

for p in portfolio:
    for deal in deals:
        if p[0] == deal[1]:
            if deal[0] == 'Buy':
                p[1] = str(int(p[1])   int(deal[2]))
            elif deal[0] == 'Sell':
                p[1] = str(int(p[1]) - int(deal[2]))

The result is: [['XYZ', '1138'], ['ABC', '42']]

  • Related