Home > Back-end >  Remove duplicated items in one list and add items with same index position in second list
Remove duplicated items in one list and add items with same index position in second list

Time:11-14

I have two lists x and y and each item in x is pointing to corresponding position in y

x = [1,2,3,4,2,3]
y = [30, 40, 10, 80, 100,40]

I want to get as:

x=[1,2,3,4]  
y=[30,140,50,80]

Overall, remove duplicated items in x and add items in y with corresponding index positions

CodePudding user response:

I'd suggest you create a dict where the key is the value from x and the value is sum of values from y using index from x

Then zip to passe from pairs [(1, 30), (2, 140), (3, 50), (4, 80)] back to x,y lists

x = [1, 2, 3, 4, 2, 3]
y = [30, 40, 10, 80, 100, 40]

results = defaultdict(int)
for i, vx in enumerate(x):
    results[vx]  = y[i]
print(results)  # {1: 30, 2: 140, 3: 50, 4: 80}

new_x, new_y = zip(*results.items())
print(new_x)  # (1, 2, 3, 4)
print(new_y)  # (30, 140, 50, 80)

CodePudding user response:

A super basic approach could be using a good old loop:

res = {}
for i1, i2 in zip(x, y):
    res[i1] = res.get(i1, 0)   i2 # if i1 not in res, will default to 0

x = list(res.keys())
y = [res[i] for i in x]

CodePudding user response:

Creating a dictionary to approach this problem will be easier-

d = dict()
for i in range(len(x)):
    if x[i] in d:
        d[x[i]]  = y[i]
    else:
        d[x[i]] = y[i]

print(d)

Once you create the dictionary 'd' with desired result, you can create new x, y lists by obtaining the keys and values of that dictionary using list() command-

x, y = list(d) , list(d.values())

print(x)
print(y)

CodePudding user response:

Try this code

Just creates a new list of zeroes, whose length is based on the difference between length of list x and length of set of list x, and add the value of y to the value in the corresponding index (from the x list) into the res list

x = [1, 2, 3, 4, 2, 3]
y = [30, 40, 10, 80, 100,40]

res = [0]*len(set(x))

for i, j in enumerate(x):
    res[j-1]  = y[i]

print(res)

Output:

[30, 140, 50, 80]

Tell me if its not working...

  • Related