Beginner : removing tuples from a list
Roman Suzi
rnd at onego.ru
Sat Feb 8 15:52:35 EST 2003
On Sat, 8 Feb 2003, Fabrizio 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']
>
>x = 0
>for z in t :
> if z[2] in europe :
> t.pop(x)
> x = x +1
>
>print t
>
>>>> [(1, 'john', 'usa'), (3, 'jeanne', 'f'), (4, 'jack', 'usa')]
Probably filter() function could help:
>>> t = [(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>>> europe = ['uk','f']
>>> print filter(lambda x: not x[2] in europe, t)
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
List comprehensions could help too:
>>> print [x for x in t if x[2] not in europe]
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
(solution is for Python 2.x, for Python 1.5.2:
>>> t = [(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>>> europe = ['uk','f']
>>> print filter(lambda x, m=europe: not x[2] in m, t)
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>But Jeanne is still there...
>
>TIA for your help
>
>
>Fabrizio
>
>
>
>
>
Sincerely yours, Roman Suzi
--
rnd at onego.ru =\= My AI powered by Linux RedHat 7.3
More information about the Python-list
mailing list