TIMEX
TIMEX

Reputation: 272334

How do I remove something form a list, plus string matching?

[(',', 52),
 ('news', 15),
 ('.', 11),
 ('bbc', 8),
 ('and', 8),
 ('the', 8),
 (':', 6),
 ('music', 5),
 ('-', 5),
 ('blog', 4),
 ('world', 4),
 ('asia', 4),
 ('international', 4),
 ('on', 4),
 ('itunes', 4),
 ('online', 4),
 ('digital', 3)]

Suppose I have this list, with tuples inside.

How do I go through the list and remove elements that don't have alphabetical characters in them?

So that it becomes this:

[('news', 15),
 ('bbc', 8),
 ('and', 8),
 ('the', 8),
 ('music', 5),
 ('blog', 4),
 ('world', 4),
 ('asia', 4),
 ('international', 4),
 ('on', 4),
 ('itunes', 4),
 ('online', 4),
 ('digital', 3)]

Upvotes: 2

Views: 496

Answers (5)

ghostdog74
ghostdog74

Reputation: 343097

@OP, just go through the list items one by one, and check the first element of each item. This is just our simple and basic thought process. No need to think too deeply about being pythonic or not, or using fanciful list comprehensions etc.. keep everything simple.

l = [(',', 52),
 ('news', 15),
 ('.', 11),
 ('bbc', 8),
 ('and', 8),
 ('the', 8),
 (':', 6),
 ('music', 5),
 ('-', 5),
 ('blog', 4),
 ('world', 4),
 ('asia', 4),
 ('international', 4),
 ('on', 4),
 ('itunes', 4),
 ('online', 4),
 ('digital', 3)]

for item in l:
    if item[0].isalpha():
        print item

output

$ ./python.py
('news', 15)
('bbc', 8)
('and', 8)
('the', 8)
('music', 5)
('blog', 4)
('world', 4)
('asia', 4)
('international', 4)
('on', 4)
('itunes', 4)
('online', 4)
('digital', 3)

Upvotes: 1

YOU
YOU

Reputation: 123917

you could use built-in filter function too, Its dedicated to that purpose actually.

filter(lambda x:x[0].isalpha(),LIST)

The result is like this

[('news', 15), 
('bbc', 8), 
('and', 8), 
('the', 8), 
('music', 5), 
('blog', 4), 
('world', 4), 
('asia', 4),
('international', 4), 
('on', 4), 
('itunes', 4), 
('online', 4), 
('digital', 3)]

Upvotes: 0

sth
sth

Reputation: 229894

Easiest should be a list comprehension with a regular expression:

import re

lst = [...]
lst = [t for t in lst if re.search(r'\w', t[0])]

Upvotes: 3

Stephan202
Stephan202

Reputation: 61609

This uses string.ascii_letters, but SilentGhost's solution is to be preferred.

>>> from string import ascii_letters
>>> [(a, b) for a, b in l if all(c in ascii_letters for c in a)]
[('news', 15), ('bbc', 8), ('and', 8), ('the', 8), ('music', 5), ('blog', 4), ('world', 4), ('asia', 4), ('international', 4), ('on', 4), ('itunes', 4), ('online', 4), ('digital', 3)]

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 319979

the_list = [(a, b) for a, b in the_list if a.isalpha()]

Upvotes: 10

Related Questions