开发者

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开发者_Python百科', 8),
 ('and', 8),
 ('the', 8),
 ('music', 5),
 ('blog', 4),
 ('world', 4),
 ('asia', 4),
 ('international', 4),
 ('on', 4),
 ('itunes', 4),
 ('online', 4),
 ('digital', 3)]


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


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])]


@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)


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)]


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)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜