给你: list1 = [2, "berry", "joe", 3, 5, 4, 10, "happy", "sad"]
想要返回 [2, 3, 5, 4, 10]
是否可以只从列表中删除字符串?
给你: list1 = [2, "berry", "joe", 3, 5, 4, 10, "happy", "sad"]
想要返回 [2, 3, 5, 4, 10]
是否可以只从列表中删除字符串?
使用列表理解,您可以仅使用您想要的元素构建另一个列表。
>>> 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]