change an element of a list

D

Dirk Hagemann

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. But as far as
I know the replace function of the module string does not work for
lists.

Any ideas? Thanks for some help!

Dirk
 
B

bruno modulix

Dirk said:
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 = tuple(l)

my_replace(lists, 'None', 'NULL')

HTH


--
bruno desthuilliers
ruby -e "print '(e-mail address removed)'.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 '(e-mail address removed)'.split('@')])"
 
D

Dirk Hagemann

THANKS! That works :)

But meanwhile I found another solution that works in my case. Out of
this list of tuples I generated a SQL-Statement which is a simple
string. Then I simply checked this string for 'None'. May be too
easy...

Dirk
 
B

bruno modulix

Dirk said:
THANKS! That works :)

Of course it works. Why wouldn'it it work ?-)
But meanwhile I found another solution that works in my case. Out of
this list of tuples I generated a SQL-Statement which is a simple
string. Then I simply checked this string for 'None'. May be too
easy...

Nope, why ? If you need to turn this list into a string anyway, doing a
replace on the string is of course the simplest and most obvious solution.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,317
Members
48,003
Latest member
coldDuece

Latest Threads

Top