[(',', 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)]
假设我有这个列表,里面有元组。
如何浏览列表并删除其中没有字母字符的元素?
这样就变成了这个:
[('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 :(得分:10)
the_list = [(a, b) for a, b in the_list if a.isalpha()]
答案 1 :(得分:3)
最简单的应该是带有正则表达式的列表理解:
import re
lst = [...]
lst = [t for t in lst if re.search(r'\w', t[0])]
答案 2 :(得分:1)
@OP,只需逐个浏览列表项,然后检查每个项目的第一个元素。这只是我们简单而基本的思考过程。不需要过于深入思考pythonic与否,或使用奇特的列表理解等等。保持一切简单。
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
输出
$ ./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)
答案 3 :(得分:0)
这使用string.ascii_letters
,但SilentGhost's solution是首选。
>>> 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)]
答案 4 :(得分:0)
您也可以使用内置的过滤器功能,它实际上是专门用于此目的。
filter(lambda x:x[0].isalpha(),LIST)
结果是这样的
[('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)]