我有以下清单:[['F','G','C'],['S',3,7],['C',3,'D']]
但我希望:[['F','G','C'],['S'],['C','D']]
列表中的元素都是str对象。所以基本上这个问题是问我怎么能让python识别一个数字,即使它被转换为字符串?
答案 0 :(得分:3)
您需要嵌套list comprehension和isinstance()
:
>>> 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']]