By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,172 Members | 762 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,172 IT Pros & Developers. It's quick & easy.

change an element of a list

P: n/a
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

Sep 15 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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 'o****@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 'o****@xiludom.gro'.split('@')])"
Sep 15 '05 #2

P: n/a
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

Sep 15 '05 #3

P: n/a
Dirk Hagemann wrote:
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.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 15 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.