Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

regex

list

[(',', 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)]
like image 949
TIMEX Avatar asked Nov 17 '25 21:11

TIMEX


2 Answers

the_list = [(a, b) for a, b in the_list if a.isalpha()]
like image 98
SilentGhost Avatar answered Nov 20 '25 12:11

SilentGhost


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])]
like image 28
sth Avatar answered Nov 20 '25 12:11

sth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!