selected printing from lists (extended)

Jorn Verwey jorn.verwey at psi.ch
Fri May 18 11:26:38 EDT 2001


Hello,

I asked a question just the other day:

> How can I avoid typing %(l[0],l[1]) in the following case?
> ->> l=[4,14]
> ->> print '%d %d' %(l[0],l[1])
>
> would like something more in the line of:
>
> ->> print '%d %d' %(l[i], for i in range(2))
>
> for longer lists.

and got a very useful response.

Carel Felling sent me the following:
>
> >>> class C:
> ...    def __init__(self, lst):
> ...      self.lst = lst
> ...    def __getitem__(self,key):
> ...      return self.lst[eval(key)]
> ...
> >>> l=[1,2,3,4,5,6,7,8,9]
> >>> "%(1)d %(2+3)d" % C(l)
> '2 6'

As I am locked up in Switzerland and he carries the same non-Swiss passport as I, I couldn't resist
to follow up his response with another question in my native tongue. He delivered again, and as I
should have used the newsgroup to ask him to begin with, I copy his reply.

My question was if I could use different lists selectively in my print statement.

>>> lst1 = [10,11,12,13,14,15]
>>> lst2 = [20,21,22,23,24,25]
>>> class C:
...     def __init__(self, **kws):
...         self.no_globals = {"__builtins__": {}}
...         self.locals = kws
...     def __getitem__(self, key):
...         return eval(key, self.no_globals, self.locals)
...

>>> "%(a[1])s %(b[c])s" % t.C(a=lst1, b=lst2, c=3)
'11 23'

>>> "%(a[int(1.3)])s" % t.C(a=lst1)
..
TypeError: bad argument type for built-in operation

>>> "%(a[int(1.3)])s" % t.C(a=lst1, int=int)
'11'

Thank you Carel.

Jorn




More information about the Python-list mailing list