Home > Enterprise >  Change number of occurrences in list
Change number of occurrences in list

Time:01-10

I have a list of lists. The last item in each list is the QTY. What I need to do is change this list so that if the first 3 items are already in the list, add 1 to the qty item in the list. Here is what I have so far, but after 1 becomes 2, now its not matching.

x = [[1,2,3,1], ['x', 'y', 'z',1], ['a', 'bv', 'sdf',1], ['x', 'y', 'z',1], ['x', 'y', 'z',1]]

new_list = []
for item in x:
    if item not in new_list:
        new_list.append(item)
    else:
        index = new_list.index(item)
        qty = new_list[index][3]
        qty  = 1
        item[3] = qty
        new_list[index] = item

print(new_list)

Output of the above code:

[[1, 2, 3, 1], ['x', 'y', 'z', 2], ['a', 'bv', 'sdf', 1], ['x', 'y', 'z', 1]]

What the output needs to look like:

[[1, 2, 3, 1], ['x', 'y', 'z', 3], ['a', 'bv', 'sdf', 1]]

Thanks

CodePudding user response:

I had the same idea as @thebjorn, but he was quicker. Here is another implementation:

import collections

x = [[1,2,3,1], ['x', 'y', 'z',1], ['a', 'bv', 'sdf',1], ['x', 'y', 'z',1], ['x', 'y', 'z',1]]

summary = collections.defaultdict(int)
for a,b,c,qty in x:
    summary[(a,b,c)]  = qty 
result = [[*k, v] for k, v in summary.items()]

print(result)
# [[1, 2, 3, 1], ['x', 'y', 'z', 3], ['a', 'bv', 'sdf', 1]]

CodePudding user response:

You can use a dict to keep track of the count:

x = [[1,2,3,1],
     ['x', 'y', 'z',1],
     ['a', 'bv', 'sdf',1],
     ['x', 'y', 'z',1],
     ['x', 'y', 'z',1]]

count = {}
for item in x:
    key = tuple(item[:3])  # dict keys can't be lists
    if key in count:
        count[key]  = item[3]
    else:
        count[key] = item[3]

new_list = [list(key)   [val] for key, val in count.items()]

print(new_list)

which outputs:

c:\srv\tmp> py -3.10 listoccur.py
[[1, 2, 3, 1], ['x', 'y', 'z', 3], ['a', 'bv', 'sdf', 1]]
  •  Tags:  
  • Related