在python中只从列表中获取数字和字母

时间:2017-02-04 20:20:07

标签: python

我有一个列表如下:

['[',
 'Persuasion',
 'by',
 'Jane',
 'Austen',
 '1818',
 ']',
 'Chapter',
 '1',
 'Sir',
 'Walter',
 'Elliot',
 ',',
 'of',
 'Kellynch',
 'Hall',
 ',',
 'in',
 'Somersetshire',
 ',',
 'was',
 'a',
 'man',
 'who',
 ',']

我只需要获得如下数字和字词:

['Persuasion',
 'by',
 'Jane',
 'Austen',
 '1818',
 'Chapter',
 '1',
 'Sir',
 'Walter',
 'Elliot',
 'of',
 'Kellynch',
 'Hall',
 'in',
 'Somersetshire'
 'was',
 'a',
 'man',
 'who']

请在这里帮忙。

感谢。

1 个答案:

答案 0 :(得分:5)

只需使用列表理解和str.isalnum

过滤您的列表
new_l = [x for x in l if x.isalnum()]

不仅包含字母或数字的字符串将不匹配(空字符串也不匹配,所以这也很好)

结果:

['Persuasion', 'by', 'Jane', 'Austen', '1818', 'Chapter', '1', 'Sir', 'Walter', 'Elliot', 'of', 'Kellynch', 'Hall', 'in', 'Somersetshire', 'was', 'a', 'man', 'who']
相关问题