best way to do some simple tasks

Mark McEahern marklists at mceahern.com
Thu Jan 30 00:46:55 CET 2003


> 1) String interpolation of lists and dictionaries
>    What is the correct and best way to do this?
>    x =[1,2,3,4]
>    print "%(x[2])i blah" % vars() # <- does not work

print '%d blah' % x[2]

lookup string formatting operations.  Python doesn't have string
interpolation AFAIK, although there's been PEP(s?) for it.

> 2) Perform a method on each element of an array
>    a= ["  hello  ",  "  there  "]
>
>    how do I use the string's strip() method on each element of the
> list?
>
>    a = map((lambda s: s.strip()), a) # looks ugly to me
>
>    for e in a:                       # this looks even worse
>       temp.append(e.strip())
>    a=temp

a = [x.strip() for x in a]

> 3) What is the best way to do this?
>
>    a=[1,2,3]
>    b=[1,1,1]
>
>    how do I get c=a+b (c=[2,3,4])?
>
>    If I wanted to use reduce(), how do I shuffle the lists?

One way:

  import operator
  c = map(operator.add, a, b)

> 4) Why does this work this way?
>    d=[1,2,3,4,5]
>    for h in d:
>       h+=1
>    print d
>    >>>[1, 2, 3, 4, 5]
>
>    Is there a python reason why h is a copy not a reference to the
> element in the list?  In perl the h would be a ref.  If d was a tuple
> I could understand it  working this way.

ints are immutable, lists aren't.

a = range(1,5)
b = [x+1 for x in a]

Cheers,

// m

-






More information about the Python-list mailing list