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 )*60+(time[1:2] or ) ```

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

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

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 )*60+(time[1:2] or )

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

Slices do not produce runtime errors for out of bound indexes. 'or' shortcircuit hack is also used for this receipt. A. Bass 17 years, 9 months ago

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)*60 + (len(time)>1 and time) N N (author) 17 years, 9 months ago

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)*60 + (ln>1 and time)
``````

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]+)*60+(time[1:2]+)
`````` Created by N N on Mon, 16 Feb 2004 (PSF)

### Required Modules

• (none specified)