我有以下列表:[['F','G','C'],['S',3,7],['C',3,'D']]
但我想拥有:[['F','G','C'],['S'],['C','D']]
列表中的元素都是str对象。所以基本上这个问题是问我如何才能让python识别一个数字,即使将其转换为字符串也是如此?
您需要一个嵌套列表理解和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']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句