Home > Enterprise >  How to iterate over nested list to input missing values
How to iterate over nested list to input missing values

Time:10-31

I have two objects, a variable (username), and a list (products) of products and costs

usernames = ['Dave','mary','John']

products (nested list)
[['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],
['pr1', '23.0', 'pr2', '45,4']]

All prices are unique to each customer. Similarly, the product set is also unique to each customer, so I cant say take a specific index such as products[0] and it would always be 'pr1'.

I've zipped the two objects together:

for x,y in zip(usernames,products):
            print(x,y)
>>>> dave, ['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0']

This gets me part way there, but I cant figure out how to append in the missing Products and 'N/A' for each username.

My end goal is a view that looks like this, dropping the 'pr' product keys so that I can use this to visualise the data:


dave ['40.0', '50.0', 'N/A', '70.0']
Mary ['N/A', '35.5', '36.0, '65.5']
John ['23.0, '45.4', 'N/A', 'N/A']


Please help Python masters, I've been trying everything for hours and I'm all out of ideas..

CodePudding user response:

you can try dict

usernames = ['Dave','mary','John']

products = [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'],['pr1', '23.0', 'pr2', '45,4']]
def get_products(data):
    template = {f'pr{i}': 'N/A' for i in range(1,5)}
    template.update(**data)
    return list(template.values())

d = [dict([p[i:i 2] for i in range(0,len(p),2)]) for p in products]
result = [get_products(i) for i in d]
print(result)

# [['40.0', '50.0', 'N/A', '70.0'], 
# ['N/A', '35.5', '36.0', '65.5'], 
# ['23.0', '45,4', 'N/A', 'N/A']]

CodePudding user response:

import numpy as np


usernames = ['Dave','mary','John']
products= [['pr1', '40.0', 'pr2', '50.0', 'pr4', '70.0'],['pr2', '35.5', 'pr3', '36.0', 'pr4', '65.5'], ['pr1', '23.0', 'pr2', '45,4']]
product_list = ['pr1', 'pr2', 'pr3', 'pr4']

product_price = {i:[] for i in product_list}

for user, product in zip(usernames, products):
    for pr, price in zip(product[0::2], product[1::2]):
        product_price[pr].append(price)
    for item in set(product_list)-(set(product[0::2])):
        product_price[item].append(np.nan)
        
for i, user in enumerate(usernames):
    print (user, [product_price[k][i] for k in product_list])

Output

Dave ['40.0', '50.0', nan, '70.0']
mary [nan, '35.5', '36.0', '65.5']
John ['23.0', '45,4', nan, nan]
  • Related