Welcome, guest | Sign In | My Account | Store | Cart

'.get()' functionality of mappings for sequences

Python, 2 lines
1
2
time=(2,5)
all_minutes=(time[0:1] or [0])[0]*60+(time[1:2] or [0])[0]

to get element number 'n' from list 'lst' and default value 'default' use:

(lst[n:n+1] or [default])[0]

When using mappings we can use something like:

time={"hours":2,"minutes":5} time={"hours":2} all_minutes=time.get("hours",0)*60+time.get("minutes",0)

But sometimes we get a sequence instead of a mapping:

time=(2,5) time=(2,) time=map(int,raw_input().split(":"))

all_minutes=(time[0:1] or [0])[0]*60+(time[1:2] or [0])[0]

can replace things like: time=(2,5) all_minutes=0 if len(time)>0: ....all_minutes+=time[0]*60 if len(time)>1: ....all_minutes+=time[1]

Slices do not produce runtime errors for out of bound indexes. 'or' shortcircuit hack is also used for this receipt.

2 comments

A. Bass 20 years, 1 month ago  # | flag

Your already using the 'or shortcircuit hack', so why not use the 'and shortcircuit hack' and skip the 1 element slice and lookup altogether:

time=(2,5)

all_minutes=(len(time)>0 and time[0])*60 + (len(time)>1 and time[1])

N N (author) 20 years, 1 month ago  # | flag

Looks fine. And while where at it, we could factor "len(time)" out:

time=(2,5)
ln=len(time)
all_minutes=(ln>0 and time[0])*60 + (ln>1 and time[1])

I probably should have used another example. The problem is, this last version only works for default values of 0.

By the way here is another way of doing this, avoiding shortcircuit. Dunno if there is any benefit to it:

all_minutes=(time[0:1]+[0])[0]*60+(time[1:2]+[0])[0]
Created by N N on Mon, 16 Feb 2004 (PSF)
Python recipes (4591)
N N's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks