Beginner : removing tuples from a list
Paul Nilsson
python.newsgroup at REMOVE.paulnilsson.com
Sat Feb 8 15:52:07 EST 2003
On Sat, 08 Feb 2003 20:03:41 GMT, an infinite amount of monkeys
hijacked the computer of "Fabrizio" <facelle at libero.it> and wrote:
>Hi,
>
>I have a list containing tuples ("records") :
>
>t = [(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>
>I want to remove all the "european records". I tried the following, but it
>doesn't work :
>
>europe = ['uk','f']
You're reading the list as you pop() elements which is why the result
is wrong. The following modification should work:
x = 0
for z in t[:] : # copy the list
if z[2] in europe :
print "woo"
t.pop(x)
else:
x = x +1 #only advance the counter if no delete
print t
It's not very obvious what you're trying to do. You can use filter
her, it filters calls a function for each element in a list, if the
function returns 0 the element is removed e.g.
def not_in_europe(c):
europe = ['uk','f']
return c[2] not in europe
t = filter(not_in_europe, t)
of course you could replace all that with a lambda function so your
entire code is:
>t = [(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>europe = ['uk','f']
>t = filter(lambda x: x[2] not in europe, t)
More information about the Python-list
mailing list