你被给予: list1 = [2,&#34; berry&#34;,&#34; joe&#34;,3,5,4,10,&#34; happy&#34;,&#34; sad&#34;] < / p>
想要回归 [2,3,5,4,10]
是否可以从列表中删除字符串?
答案 0 :(得分:1)
使用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]