你得到: list1 = 2,“浆果”,“乔”,3,5,4,10,“快乐”,“悲伤”
想返回2,3,5,4,10
是否可以仅从列表中删除字符串?
发布于 2012-06-08 13:10:55
使用a list-comprehension,您可以构造另一个仅包含所需元素的列表。
>>> list1 = [2, "berry", "joe", 3, 5, 4, 10, "happy", "sad"]
>>> [i for i in list1 if isinstance(i, int)]
[2, 3, 5, 4, 10]例如,如果您也有浮点数,并希望保留这些浮点数,则可以选择:
>>> list1 = [2, "berry", "joe", 3, 5, 4, 10.0, "happy", "sad"]
>>> [i for i in list1 if not isinstance(i, str)]
[2, 3, 5, 4, 10.0]https://stackoverflow.com/questions/10943219
复制相似问题