change an element of a list
bruno modulix
onurb at xiludom.gro
Thu Sep 15 06:26:26 EDT 2005
Dirk Hagemann wrote:
> Hi!
>
> I have a list of lists and in some of these lists are elements which I
> want to change.
> Here an example:
> lists=[('abc', 4102, 3572), ('def', 2707, 'None'), ('ghi', 'None', 4102)]
>
> 'None' should be replaced by 0 or NULL or something else.
Your list is a list of tuples, and what you want here is to replace an
element of a tuple - which is not directly possible since tuples are
immutables (but of course there's a way... !-)
> But as far as
> I know the replace function of the module string does not work for
> lists.
Nope, but you can still replace or modify an element of a list.
here a (very Q&D and probably naive and suboptimal) possible solution:
def my_replace(alist, target, replacement):
"""Takes a list of tuples and for each tuple
'replace' target with 'replacement
"""
for i, t in enumerate(alist):
l = list(t)
while target in l:
l[l.index(target)] = replacement
alist[i] = tuple(l)
my_replace(lists, 'None', 'NULL')
HTH
--
bruno desthuilliers
ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p|
p.split('.').collect{|w| w.reverse}.join('.')}.join('@')"
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list