Python Forum
splitting lines, need to add element of same kind
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
splitting lines, need to add element of same kind
#6
If anything is to be counted my first thought is to go for Counter which happens to be Python's data type for counting.

Assuming that file data.csv containing sample data one can achieve desired output (in descending order):

from collections import Counter
from datetime import datetime as dt


with open('data.csv', 'r') as f:
    count = Counter()
    for line in f:
        _, marker, qty, item = line.strip().split(',')
        count.update({item: int(qty)})

timestamp = dt.today().date().strftime("%d/%m/%Y")

for item, qty in count.most_common():              # for ascending order: count.most_common()[::-1]
    print(f'{timestamp},{marker},{qty},{item}')     

20/02/2021,P,20,fish
20/02/2021,P,15,dog
20/02/2021,P,10,cat
tester_V likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
RE: splitting lines, need to add element of same kind - by perfringo - Feb-20-2021, 07:11 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  What kind of list is this? jesse68 2 1,185 Jun-29-2022, 05:02 PM
Last Post: rob101
  What kind of object is this? Moris526 5 2,594 Dec-27-2020, 06:41 AM
Last Post: Gribouillis
  Iterate 2 large text files across lines and replace lines in second file medatib531 13 6,054 Aug-10-2020, 11:01 PM
Last Post: medatib531
  How to do this kind of IF STATEMENT? glennford49 4 2,714 Jun-17-2020, 09:45 AM
Last Post: glennford49
  Splitting lines ang grouping three at once samsonite 5 2,844 Jun-21-2019, 05:19 PM
Last Post: ichabod801
  Unable to locate element no such element gahhon 6 4,570 Feb-18-2019, 02:09 PM
Last Post: gahhon
  How to write a code to get this kind of output in IDLE kavindu 5 3,619 Oct-28-2018, 07:46 PM
Last Post: wavic
  Newbie question for a kind of rolling average of list of lits zydjohn 3 3,383 Dec-16-2017, 11:41 PM
Last Post: ezdev
  Change single element in 2D list changes every 1D element AceScottie 9 12,176 Nov-13-2017, 07:05 PM
Last Post: Larz60+
  Compiler fault or some kind of weird referencing bug? Joseph_f2 11 9,262 May-09-2017, 08:50 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

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