Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Array Iteration/Merging
#1
Hello All,

So let me get straight to my issue, I've got nested array which is a result set from a SQL query and has the format similar to the below.

'Resp' is the only unique column and 'ticket' often has duplicates.

[[ticket,resp,quantity]]
So for example if the array is printed (for x in x) you would get the below sample data

[56789,1326,10]
[12345,2365,1]
[56789,2542,20]
[12345,8468,5]
What I'm looking to do is add the 'quantity' field where the 'ticket' numbers are the same and produce a new nested array, the unique resp could be dropped at this point as I’m not sure if it's needed yet. The above sample data would become the below

[56789,xxxx,30]
[12345,xxxx,6]
I've tried a few things but never quite seem to get it working. Any advice or directing would be appreciated.
I hope I've been clear enough?
Reply
#2
This response will work for you too - just drop column 1 and use sum as an aggregation function
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Thanks Volcano63,

That's exactly what I'm looking for Smile

I really should have done a better job of searching.
Reply
#4
well, to be honest I would alter the SQL query to get the what I want
SELECT ticket, SUM(quantity) FROM table GROUP BY ticket

data = [[56789,1326,10],
        [12345,2365,1],
        [56789,2542,20],
        [12345,8468,5]]

result = {}       
for ticket, resp, quantity in data:
    result[ticket] = result.get(ticket,0) + quantity

print(result)
or using defaultdict

from collections import defaultdict
data = [[56789,1326,10],
        [12345,2365,1],
        [56789,2542,20],
        [12345,8468,5]]

result = defaultdict(int)       
for ticket, resp, quantity in data:
    result[ticket]+=quantity

print(result)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Hi Buran,

Altering my query does make a lot of sense, get the data I want and save messing with it more than I have to in Python.

Thanks for the suggestion, I'll give it a go as we
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Iteration of an array PappaBear 5 2,734 May-23-2019, 06:54 PM
Last Post: PappaBear

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020