Home > Mobile >  How to display the missing part of a sorted line data using lambda
How to display the missing part of a sorted line data using lambda

Time:12-07

I am trying to improve the snippet below. I tried some modification but its not working to create the wanted output. What part needs to be modified to get the output I wanted? Thanks in advance.

from collections import defaultdict

data=defaultdict(int)
num = 0
with open("Samplefile.txt", encoding='utf8', errors='ignore') as f:
    for line in f:
        grp, pname, cnt, cat = line.split(maxsplit=3)
        data[(pname.strip(),cat.replace('\n','').strip(),grp)] =int(cnt)
        
sorteddata = sorted([[k[0],v,k[2]] for k,v in data.items()], key=lambda x:x[1], reverse=True)

for subl in sorteddata[:10]:
    num  = 1
    line = " ".join(map(str, subl))
    print ("{:>5}  -> {:<5}".format(str(num), line))

Samplefile.txt

  113   b6320070eb6998e64d2d6573fc  4  Yorkie (YORK)
2,887   0953f9e6608d6604e4676ac5b7  3  Fins LPs (FINS-L...)
  122   74c33cff9ff98f3a9b62fcbff5  3  Fins Token (FINS)
  128   f9fa0a842465d9a2f5f9fd1423  2  Numbers One (NUM)
1,272   4230cbfda057d8ec2c48abe2a2  2  USDC (anyUSD...)

Current Output: #

1  -> b6320070eb6998e64d2d6573fc 4 113
2  -> 0953f9e6608d6604e4676ac5b7 3 2,887
3  -> 74c33cff9ff98f3a9b62fcbff5 3 122
4  -> f9fa0a842465d9a2f5f9fd1423 2 128
5  -> 4230cbfda057d8ec2c48abe2a2 2 1,272

Wanted Output:

1  ->   113   b6320070eb6998e64d2d6573fc   4   Yorkie (YORK)
2  -> 2,887   0953f9e6608d6604e4676ac5b7   3   Fins LPs (FINS-L...)
3  ->   122   74c33cff9ff98f3a9b62fcbff5   3   Fins Token (FINS)
4  ->   128   f9fa0a842465d9a2f5f9fd1423   2   Numbers One (NUM)
5  -> 1,272   4230cbfda057d8ec2c48abe2a2   2   USDC (anyUSD...)

CodePudding user response:

Your sortedData list, reorganized the content of the key and value. You'll have to take that into consideration in your print formatting:

for num,(k0,v,k2) in enumerate(sorteddata[:10],1):
     print(f"{num:5} -> {k2:>5} {k0} {v}")

Still, this will not print the last part (e.g. 'Yorkie (YORK)') because you removed it from the sorted list completely so it is no longer accessible in sortedData (you need to keep it in there to be able to print it)

  • Related