Python,从子列表中删除所有数字

时间:2016-05-02 01:01:43

标签: python string types casting int

我有以下清单:[['F','G','C'],['S',3,7],['C',3,'D']]

但我希望:[['F','G','C'],['S'],['C','D']]

列表中的元素都是str对象。所以基本上这个问题是问我怎么能让python识别一个数字,即使它被转换为字符串?

1 个答案:

答案 0 :(得分:3)

您需要嵌套list comprehensionisinstance()

>>> l = [['F', 'G', 'C'], ['S', 3, 7], ['C', 3, 'D']]
>>> [[item for item in sublist if not isinstance(item, int)] for sublist in l]
[['F', 'G', 'C'], ['S'], ['C', 'D']]

如果您还需要处理字符串中的数字,str.isdigit()会有所帮助:

>>> l = [['F', 'G', 'C'], ['S', '3', '7'], ['C', '3', 'D']]
>>> [[item for item in sublist if not item.isdigit()] for sublist in l]
[['F', 'G', 'C'], ['S'], ['C', 'D']]