python hints 4

Read a File in a sort

#Example to read in a delimited file - and to sort it.

#t.t looks like
#
#N0NB       40860 180 1259287868
#A45WG      40840 150 1452258192
#KI4FND     39218 160 1201066934
#W9YA       38957 165 1192869212
#


LINES=(open('t.t')).readlines()
#Read 1
LINE_TUP=[]
for a in LINES:
    b=a.split()
    LINE_TUP.append((b[0],b[1],b[2],b[3]))

#or
LINE_TUP=[tuple((a.split()[0:4])) for a in LINES]

#
#Sorts using a Lambda
#Very cool
#
rows_by_speed = sorted(LINE_TUP, key=lambda r: int(r[2]),reverse=True)
rows_by_score = sorted(LINE_TUP, key=lambda r: int(r[1]),reverse=True)

Good example of creating tuples from a line using a split.

Plus good use of sort and lambda

Where is my Callsign in this list ?

Becuase the list is a list of Tuples a straight .index will not work.

[a[0] for a in LINE_TUP ].index('A45WG')
>>77

Hex Dump a string

a="I am a String"
hex_a=":".join("{:02x}".format(ord(c)) for c in s)

Recursion example

 a='ANDTLGY'

def chopper(s,chop=3):
     if len(s) < chop:
        return []
     return [s[0:chop]] + chopper(s[1:],chop)